[Excerpt-socket-Learning]socket listen for local IP (inaddr_any) and get local IP address
Source: Internet
Author: User
1, the server is not fixed IP listening, only monitoring the host any IP address: (the client specifies the local IP address, the server does not need to modify any IP address information) bzero (&adr_inet, sizeof (adr_inet)); adr_inet.sin_family = af_inet; ADR_INET.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Adr_inet.sin_port = htons (port);
Note: The dual IP address of the host has not been processed, to be verified;
2, obtain the local IP address: (no TCP and UDP points)//Remove the local IP address struct sockaddr_in serv; Char serv_ip[20]; int serv_len = sizeof (serv); GetSockName (SOCKFD, struct sockaddr *) &serv, (socklen_t *) &serv_len); Inet_ntop (Af_inet, &serv.sin_addr, serv_ip, sizeof (SERV_IP)); printf ("Local address:%s\n", serv_ip);
3. Get local IP Address: (no TCP and UDP) Udp:recvlen = Recvfrom (sockfd, buf, sizeof (BUF), 0, (struct sockaddr *) &adr_clnt, (Socklen_ T *) &len); if (Recvlen < 0) {usleep); continue;} char* ClientIP = Inet_ntoa (ADR_CLNT.SIN_ADDR); Long ClientPort = Ntohs (Adr_clnt.sin_port);
Tcp:accept (Listener, (struct sockaddr *) &their_addr, &socklen); char* ClientIP = Inet_ntoa (THEIR_ADDR.SIN_ADDR); Long ClientPort = Ntohs (Their_addrt.sin_port);
Note: If a socket is bundled with inaddr_any, which means that the socket can be used with the address of any host, then getsockname () will not return any information about the host's IP address unless it calls connect () or accept (). Windows socket applications should not assume that IP addresses will change from Inaddr_any to other addresses unless sockets are connected. This is because for multiple host environments, the IP address used by the socket is not known unless the socket is connected.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.