How to get socket port number if it's system assigned
来源:互联网 发布:扫码签到软件 编辑:程序博客网 时间:2024/06/06 19:49
启动服务端,让系统自动分配端口后,并把这个端口号告诉客户端,以便于客户端连接.
在bind(...)函数后使用getsockname(...)就可以获取此端口号, 代码如下:
#include <iostream>
#include <windows.h>
using namespace std;
#define PORT 0
#define IP_ADDRESS "127.0.0.1"
#if 1
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
#else
int main(int argc, char * argv)
#endif
{
WSADATA wd;
SOCKET theSock;
struct sockaddr_in theSockAddr;
int ret = 0;
int addrLen = 0;
//Init Windows Socket
if ( WSAStartup(MAKEWORD(2,2), &wd) != 0 )
{
cout << "Init Windows Socket Failed::" << GetLastError() << endl;
return -1;
}
//Create Socket
theSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( theSock == INVALID_SOCKET )
{
cout << "Create Socket Failed::" << GetLastError() << endl;
return -1;
}
theSockAddr.sin_family = AF_INET;
theSockAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
theSockAddr.sin_port = htons(PORT);
memset(theSockAddr.sin_zero, 0x00, 8);
//Bind Socket
ret = bind(theSock, (struct sockaddr*)&theSockAddr, sizeof(theSockAddr));
if ( ret != 0 )
{
cout << "Bind Socket Failed::" << GetLastError() << endl;
return -1;
}
// Get bind port number
{
struct sockaddr_in anotherSockAddr;
int len = sizeof(anotherSockAddr);
getsockname(theSock,(sockaddr *)&anotherSockAddr,&len);
unsigned short newPort = ntohs(anotherSockAddr.sin_port);
cout << "Bind Socket value is " << newPort << endl;
}
closesocket(theSock);
WSACleanup();
return 0;
}
- How to get socket port number if it's system assigned
- How to get and set the system socket buffer in AIX?
- how to check port number and kill process with the port number
- How To Get System Info In Linux
- [PHP]How to get the system info?
- How to get iPhone OS number ?
- How to change your USB Serial Port COM number?
- How to get port in FTP protocol from passive mode?
- if not to say it's different,
- How to get new record's id
- How to Get Table’s Generated Ids
- It’s Not Too Late to Learn How to Code
- It’s Not Too Late to Learn How to Code
- It’s Not Too Late to Learn How to Code
- How to get operating system info in .NET
- how to get detail system info on MAC?
- C# How to get the system drive of remote server
- iOS 7: How to get own number via private API?
- 二进制与十进制之间的转换
- Java相关的基础知识
- 这么多贱的话,总有一句贱到你心里了
- Gallery Server Pro (学习笔记)
- Excel 2007 六则技巧 帮你省时间
- How to get socket port number if it's system assigned
- Configuring Solr 1.4 logging with Log4J in Tomcat
- OnPaletteChanged(CWnd* pFocusWnd) 和OnQueryNewPalette() 的作用
- 语录
- 无奈
- 2010提升你幽默感的经典短句
- voice-family: "/"}/"";的作用
- 神奇的大脑
- 如何在不安装Word的情况下生成Word文档 ——转【陈希章】