台灣最大程式設計社群網站
線上人數
1680
 
會員總數:241752
討論主題:187055
歡迎您免費加入會員
討論區列表 >> C/C++ >> How to get port number of Socket server
[ 變換順序 ]  
[我要回覆]
回應主題 加入我的關注話題 檢舉此篇討論 將提問者加入個人黑名單
How to get port number of Socket server
價值 : 30 QP  點閱數:187 回應數:0

樓主

Blue
初學者
317 83
972 165
發送站內信

Hi,各位先進大家好:
目前改寫IPv4 to IPv6兼容
舊有的程式是用Socket 開一隨機 Port listen,
現改程式,可開 隨機 Port,但我要如何得知其 Port number, 這裡印出來的結果是 0,
謝謝!

int get_in_port(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return (((struct sockaddr_in*)sa)->sin_port);
}

return (((struct sockaddr_in6*)sa)->sin6_port);
}


int tcp_listen(const char *host, const char *service_, const int listen_num = 5)
{
SOCKET s = -1;
int listenfd_, ret;
const int on = 1;
struct addrinfo hints, *res, *ressave;
ZeroMemory(&hints, sizeof(hints));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_IP;

char *service="0";
if (0 != (ret = getaddrinfo(host, service, &hints, &res)))
{
cout << "getaddrinfo error: " << gai_strerror(ret) << endl;
return -1;
}

ressave = res;
while(NULL != res)
{
if (-1 == (s = socket(res->ai_family, res->ai_socktype, res->ai_protocol)))
{
cout << "create socket error: " << strerror(errno) << endl;
res = res->ai_next;
continue;
}

if (-1 == setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on)))
{
cout << "setsockopt error: " << strerror(errno) << endl;
closesocket(s);
res = res->ai_next;
continue;
}

if (-1 == bind(s, *&res->ai_addr, res->ai_addrlen))
{
cout << "bind error: " << strerror(errno) << endl;
closesocket(s);
res = res->ai_next;
continue;
}

if (-1 == listen(s, listen_num))
{
cout << "listen error: " << strerror(errno) << endl;
closesocket(s);
res = res->ai_next;
continue;
}
printf("port is %d\n",ntohs(get_in_port((struct sockaddr *)res->ai_addr)));
break;
}

if (NULL == res) return -1;
return s;
}




搜尋相關Tags的文章: [ Listen port number ] ,
本篇文章發表於2017-12-28 15:08
別忘捐VP感謝幫助你的人 新手會員瞧一瞧
目前尚無任何回覆
[ 變換順序 ]   

回覆
如要回應,請先登入.