C语言 套接字 - 如何找出分配给我的端口和地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4046616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sockets - How to find out what port and address I'm assigned
提问by stringo0
I'm having trouble figuring this out - I'm working with sockets in C using this guide - http://binarii.com/files/papers/c_sockets.txt
我无法弄清楚这一点 - 我正在使用本指南在 C 中使用套接字 - http://binarii.com/files/papers/c_sockets.txt
I'm trying to automatically get my ip and port using:
我正在尝试使用以下方法自动获取我的 ip 和端口:
server.sin_port = 0; /* bind() will choose a random port*/
server.sin_addr.s_addr = INADDR_ANY; /* puts server's IP automatically */
...
...
bind(int fd, struct sockaddr *my_addr,int addrlen); // Bind function
After a successful bind, how do I find out what IP and Port I'm actually assigned?
成功绑定后,如何找出实际分配给我的 IP 和端口?
回答by mark4o
If it's a server socket, you should call listen()on your socket, and then getsockname()to find the port number on which it is listening:
如果它是一个服务器套接字,你应该调用listen()你的套接字,然后getsockname()找到它正在侦听的端口号:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANYthen the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.
至于 IP 地址,如果您使用,INADDR_ANY那么服务器套接字可以接受与机器的任何 IP 地址的连接,并且服务器套接字本身没有特定的 IP 地址。例如,如果您的机器有两个 IP 地址,那么您可能会在此服务器套接字上获得两个传入连接,每个连接具有不同的本地 IP 地址。您可以getsockname()在套接字上使用特定连接(您从中获得accept()),以便找出该连接上使用的本地 IP 地址。

