BSD Sockets Invalid Argument at connection
I keep getting an invalid argument error when I try to connect the client to the server. A couple threads online said this can happen when addrlen is not right, but I tried changing it to a literal value after counting the length and that did not work. I also tried just strlen() with no luck. Anyways, relevant code -
server -
struct sockaddr name;
int main(int agrc, char** argv) {
int sock, new_sd, adrlen; //sock is this socket, new_sd is connection socket
name.sa_family = AF_INET;
strcpy(name.sa_data, "127.0.0.1");
adrlen = strlen(name.sa_data) + sizeof(name.sa_family);
//make socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
printf("\nBind error %m", errno);
exit(1);
}
//unlink and bind
unlink("127.0.0.1");
if(bind (sock, &name, adrlen) < 0)
printf("\nBind error %m", errno);
//listen
if(listen(sock, 5) < 0)
printf("\nListen error %m", errno);
//accept
new_sd = accept(sock, &name, (socklen_t*)&adrlen);
if( new_sd < 0) {
printf("\nAccept error %m", errno);
exit(1);
}
client -
int main(int agrc, char** argv) {
int sock, new_sd, adrlen;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
printf("\nserver socket failure %m", errno);
exit(1);
}
//stuff for server socket
name.sa_family = AF_INET;
strcpy(name.sa_data, "127.0.0.1");
adrlen = strlen(name.sa_data) + sizeof(name.sa_family);
cout<<"\nadrlen: "<<adrlen<<"\n";
if(connect(sock, &name, adrlen) < 0) {
printf("\nclient connection failure %m", errno);
exit(1);
}
I don't see anything that could be wrong, but I guess I might just be overlooking something or unaware of开发者_如何学Python something. Any help is appreciated.
strcpy(name.sa_data, "127.0.0.1");
Really? The address should be the 32 bit IPv4 address, not a string.
This is the structure for AF_INET (from here):
// IPv4 AF_INET sockets:
struct sockaddr_in {
short sin_family; // e.g. AF_INET, AF_INET6
unsigned short sin_port; // e.g. htons(3490)
struct in_addr sin_addr; // see struct in_addr, below
char sin_zero[8]; // zero this if you want to
};
struct in_addr {
unsigned long s_addr; // load with inet_pton()
};
Well your big problem is completely misunderstanding the sockaddr struct!
Firstly use sockaddr_in.
You would then write code more like the following:
sockaddr_in sai;
sai.sin_family = AF_INET;
sai.sin_port = htons( 12345 ); /// Or whatever port you wish to use.
inet_aton("127.0.0.1", &sai.sin_addr.s_addr);
Note: htons converts a short value from host to network format. Host could be big or little endian. Network is big endian.
精彩评论