问题描述
我在遇到麻烦搞清楚了这一点 - 我使用本指南与插座的工作用C - 的
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
我试图使用自动获得我的IP和端口:
I'm trying to automatically get my ip and port using:
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
在一个成功的绑定,我怎么找出IP和端口实际上,我分配?
After a successful bind, how do I find out what IP and Port I'm actually assigned?
推荐答案
如果它是一个服务器套接字,你应该叫<$c$c>listen()$c$c>你的插座,然后<$c$c>getsockname()$c$c>找到它正在侦听的端口号:
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:
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));
对于IP地址,如果你使用 INADDR_ANY
那么服务器插槽可以接受任何机器的IP地址和服务器套接字本身不具有特定的连接IP地址。例如,如果你的机器有两个IP地址,那么你可能会得到这个服务器套接字两个输入连接,每一个不同的本地IP地址。您可以使用 getsockname()
为了特定的连接插座(您从获得接受()
)上找出哪些本地IP地址正在该连接上使用。
As for the IP address, if you use INADDR_ANY
then 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.
这篇关于插口 - 如何找出哪些端口和地址我分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!