自己寫遠端控制軟體之偵測伺服器

LiuYinChina發表於2013-01-31
為了方便發現伺服器,主要原因是我懶得寫 IP 地址,我是這麼做的,用 UDP 每隔幾秒廣播一次,客戶端開一個執行緒在指定埠接收,收到訊息就說明傳送 UDP 地址為伺服器 IP,然後顯示在介面上,選擇,連線,就看到伺服器桌面了。

class CBoardcast
{
public:
	CBoardcast()
	{
		m_hSocket = ::WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, 0);

		bool bBroadcast	= true;
		setsockopt(m_hSocket, SOL_SOCKET, SO_BROADCAST, (char *) &bBroadcast, sizeof(bBroadcast));

		SOCKADDR_IN addrUDP	= { 0 };
		addrUDP.sin_family	= AF_INET;
		addrUDP.sin_port	= htons(0);
		addrUDP.sin_addr.s_addr = htonl(INADDR_ANY);
		bind(m_hSocket, (SOCKADDR *) &addrUDP, sizeof(addrUDP));
	}
	~CBoardcast()
	{
		closesocket(m_hSocket);
		m_hSocket = INVALID_SOCKET;
	}

	//////////////////////////////////////////////////////////////////////////

	INT Boardcast(USHORT nPort, PCHAR pBuffer, DWORD dwLength)
	{
		SOCKADDR_IN addrUDP	= { 0 };
		addrUDP.sin_family	= AF_INET;
		addrUDP.sin_port	= htons(nPort);
		addrUDP.sin_addr.s_addr = htonl(INADDR_BROADCAST);

		return sendto(m_hSocket, pBuffer, dwLength, 0, (SOCKADDR *) &addrUDP, sizeof(SOCKADDR_IN));
	}

private:
	SOCKET m_hSocket;
};

怎麼樣,簡單吧?


相關文章