How to get the ip address of the accepted in-bound socket?
c, sockets
Solution
Use `getsockname(2)` on the socket returned from `accept(2)`, not the socket returned from `bind(2)`.
Problem
My question is: Server will create a socket, bind to a given port and with address = INADDR_ANY. listen() & accept() the new connection. Then, we can get the client's ip-address from accept(). Now, I want to know the ip-address of the Server, since the host of the server has multiple NIC on it. How to know the ip-address of the network interface with which the accepted in-bound socket is from? I tried getsockname, it gave me the port number, but the ip is all-zero. Update: Here is the code: Server.c (header files are removed) ``` int main(void) { struct sockaddr_in stSockAddr; int res, addr_len, SocketFD, ConnectFD; struct sockaddr_in addr; SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(-1 == SocketFD) { perror("can not create socket"); //exit(EXIT_FAILURE); return -1; } memset(&stSockAddr, 0, sizeof stSockAddr); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(49335); stSockAddr.sin_addr.s_addr = INADDR_ANY; if(-1 == bind(SocketFD,(struct sockaddr *)&stSockAddr, sizeof stSockAddr)) { perror("error bind failed"); close(SocketFD); return -1; } printf("going to listen!\n"); if(-1 == listen(SocketFD, 10)) { perror("error listen failed"); close(SocketFD); //exit(EXIT_FAILURE); return -1; } ConnectFD = accept(SocketFD, NULL, NULL); if(0 > ConnectFD) { perror("error accept failed"); close(SocketFD); //exit(EXIT_FAILURE); return -1; } addr.sin_family = AF_INET; res = getsockname (ConnectFD, (struct sockaddr *)&addr, &addr_len); // if you remove the following comment, that means, if you call // two times of getsockname, the result will be correct. //res = getsockname (ConnectFD, (struct sockaddr *)&addr, &addr_len); printf("addr:%x\n", addr.sin_addr.s_addr); while(1) { if (getchar() == 'q') break; } close(ConnectFD); close(SocketFD); return 0; } ``` Below is client.c: ``` int main(void) { struct sockaddr_in stSockAddr; int Res; int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (-1 == SocketFD) { perror("cannot create socket"); exit(EXIT_FAILURE); } memset(&stSockAddr, 0, sizeof stSockAddr); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(49335); Res = inet_pton(AF_INET, "192.168.1.102", &stSockAddr.sin_addr); if (0 > Res) { perror("error: first parameter is not a valid address family"); close(SocketFD); exit(EXIT_FAILURE); } else if (0 == Res) { perror("char string (second parameter does not contain valid ipaddress"); close(SocketFD); exit(EXIT_FAILURE); } if (-1 == connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof stSockAddr)) { perror("connect failed"); close(SocketFD); exit(EXIT_FAILURE); } /* perform read write operations ... */ printf("client sockfd is successful\n"); while(1) { if (getchar() == 'q') break; } shutdown(SocketFD, SHUT_RDWR); close(SocketFD); return 0; } ```