defines int getpeername (int s, struct sockaddr *name, socklen_t *namelen); Describes the offset address struct sockaddr_in sa that gets the socket; int len = sizeof (SA); if (!getpeername (SOCKFD, struct sockaddr *) &sa, &len)) {printf ("Other ip:%s", Inet_ntoa (SA.SIN_ADDR)); printf ("Each other port:%d", Ntohs (Sa.sin_port));} Add: GetSockName and getpeername scheduling are important, and if the call is not timed, the address and port will not be properly obtained. TCP for servers, you can call getsockname to get local addresses and ports after bind, although that doesn't mean much. Getpeername is only called after the link is established, otherwise the address and port will not be obtained correctly, so his parameter descriptor is generally a link descriptor rather than a listener socket descriptor. For the client, the kernel will not allocate IP and port at the time of calling socket, when the call getsockname will not get the correct port and address (of course the link is not established more impossible to call Getpeername), of course, if you call bind You can use getsockname later. Want the correct address to the other side (the general client does not need this feature), you must after the link is established, the same link after the establishment, at this time the client address and port has been specified, this is the time to invoke Getpeername. UDP UDP is divided into links and no links 2 kinds (this to UDP and connect can find relevant content) UDP can not call Getpeername, but can call getsockname, and TCP, His address and port are not specified in the call socket, but UDP, which has been linked after the first call to the SendTo function, is available after the call to connect (getpeername). If you do not know each other's address and port, it is not possible to call connect.
Gets the IP and port
static void Get_peer_ip_port (int fd, char **ip, int *port)
{
int client_fd = FD
corresponding to FD; Discovery Client Information
struct sockaddr_in addr;
socklen_t Addrlen = sizeof (addr);
if (getpeername (client_fd, struct sockaddr*) &addr, &addrlen) = = 1) {
fprintf (stderr, "Discovery Client Information failed, fd=%d, errno=%d (% #x). \ n ", CLIENT_FD, errno, errno);
return;
}
IP v4 or v6
char *buf = malloc (Inet6_addrstrlen);
memset (buf, 0, Inet6_addrstrlen);
if ((Inet_ntop (addr.sin_family, &addr.sin_addr, buf, inet6_addrstrlen)) = = NULL) {
fprintf (stderr, "convert") Client information failed, fd=%d, errno=%d (% #x). \ n ", CLIENT_FD, errno, errno);
return;
}
*port = Ntohs (addr.sin_port);
fprintf (stdout, "Get peer IP of client ip=%s, port=%d, fd=%d\n", buf, *port, client_fd);
*ip = buf;
return;
}