我需要为某些程序生成端口号。谷歌告诉我,与零端口绑定生成绑定未使用的端口。我想绑定零端口,记住它的号码,关闭端口。试着这样做?但netstat没有看到我的程序端口。 Linux 2.6.27
int sfd;
struct sockaddr_in my_addr;
sfd = socket(PF_INET , SOCK_STREAM, 0);
if (sfd == -1)
{
printf("socket error\n");
return -1;
}
memset(&my_addr, 0, sizeof(struct sockaddr_in ));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = 0;
if (bind(sfd, (struct sockaddr_in *) &my_addr,
sizeof(struct sockaddr_in)) == -1)
printf("bind error\n");
if (listen(sfd, LISTEN_BACKLOG) == -1)
printf("listen error\n");
答案 0 :(得分:1)
bind()
预计sockaddr*
不是sockaddr_in*
:
bind(sfd, (struct sockaddr *) &my_addr, sizeof(my_addr))
除此之外,我没有看到任何其他错误。绑定到端口0是绑定到随机可用端口的正确方法。如果bind()
和listen()
未报告失败,则netstat应该会看到一个开放端口。使用getsockname()
找出实际选择的端口bind()
,例如:
int sfd = socket(PF_INET , SOCK_STREAM, 0);
if (sfd == -1)
{
printf("socket error: %d\n", errno);
return -1;
}
struct sockaddr_in my_addr;
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_addr.s_addr = INADDR_ANY;
my_addr.sin_port = 0;
if (bind(sfd, (struct sockaddr *) &my_addr, sizeof(my_addr)) == -1)
{
printf("bind error: %d\n", errno);
close(sfd);
return -1;
}
if (listen(sfd, LISTEN_BACKLOG) == -1)
{
printf("listen error: %d\n", errno);
close(sfd);
return -1;
}
memset(&my_addr, 0, sizeof(my_addr));
socklen_t my_addrlen = sizeof(my_addr);
if (getsockname(sfd, (struct sockaddr *) &my_addr, &my_addrlen ) == -1)
{
printf("getsockname error: %d\n", errno);
close(sfd);
return -1;
}
printf("listening on port: %hu\n", ntohs(my_addr.sin_port));