插口 - 如何找出哪些端口和地址我分配 [英] Sockets - How to find out what port and address I'm assigned

查看:117
本文介绍了插口 - 如何找出哪些端口和地址我分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在遇到麻烦搞清楚了这一点 - 我使用本指南与插座的工作用C - 的 http://binarii.com/files/papers/c_sockets.txt

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?

推荐答案

如果它是一个服务器套接字,你应该叫<一个href=\"http://www.opengroup.org/onlinepubs/9699919799/functions/listen.html\"><$c$c>listen()你的插座,然后<一个href=\"http://www.opengroup.org/onlinepubs/9699919799/functions/getsockname.html\"><$c$c>getsockname()找到它正在侦听的端口号:

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.

这篇关于插口 - 如何找出哪些端口和地址我分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆