1. 程式人生 > >Winsock:獲取UDP資料傳送端的IP地址和埠號

Winsock:獲取UDP資料傳送端的IP地址和埠號

 UDP的接收端使用函式 recvfrom接收資料,這個函式在winsock.h中定義如下:

int recvfrom(
  __in         SOCKET s,
  __out        char* buf,
  __in         int len,
  __in         int flags,
  __out        struct sockaddr* from,
  __inout_opt  int* fromlen
);

其中的引數 from 就儲存了資料傳送端的IP地址和埠號,為了便於說明,sockaddr_in結構在winsock中定義如下:

struct sockaddr_in {
        short   sin_family;
        u_short sin_port;
        struct  in_addr sin_addr;
        char    sin_zero[8];
};

sin_addr:資料傳送端的IP地址;

sin_port:資料傳送端的埠號;

所以,可以使用如下的程式碼獲取資料傳送端的IP地址和埠號:

......
CHAR szClientIP[128], szClientPort[64];
strcpy(szClientIP, inet_ntoa(from.sin_addr));
strcpy(szClientPort, itoa(ntohs(from.sin_port)));
......

函式inet_ntoa的作用是將一個IPv4的網路地址轉換成為一個標準的IP地址字串,並且以點號(.)分割,在winsock.h中定義如下:
char* FAR inet_ntoa(
  __in  struct   in_addr in
);

函式ntos的作用是將一個16的無符號數有網路位元組順序轉換成主機位元組順序,在winsock.h中定義如下:
u_short ntohs(
  __in  u_short netshort
);