在socket编程中,如何获取连接另一端(客户端)的ip地址,使用accept或者getpeername

原文链接:https://blog.csdn.net/gukesdo/article/details/6889594

//这段代码没有实际的功能,只是为了获取连接另一端的ip地址 


   
   
   
   
  1. #include
  2. #include
  3. #include
  4. #pragma comment(lib, “wsock32”)
  5. using namespace std;
  6. void main()
  7. {
  8. int ret = 0;
  9. WSADATA wsadata;
  10. WORD version = MAKEWORD( 2, 0);
  11. ret = WSAStartup(version,&wsadata);
  12. //服务器端口创建
  13. SOCKET m_hServerSocket;
  14. m_hServerSocket = socket(AF_INET,SOCK_STREAM, 0);
  15. //服务器端口绑定
  16. SOCKADDR_IN m_addr;
  17. m_addr.sin_family = AF_INET;
  18. m_addr.sin_addr.S_un.S_addr = INADDR_ANY; //如果服务器是单网卡的,则就是这块网卡的ip地址;如果是多网卡,则是其中的任意一块的ip地址
  19. m_addr.sin_port = htons( 10000);
  20. ret = bind(m_hServerSocket,(LPSOCKADDR)&m_addr, sizeof(m_addr));
  21. //服务器端口开始监听
  22. ret = listen(m_hServerSocket, 10); //第二个参数指定最大申请的连接数
  23. WSADATA cli_wsadata;
  24. ret = WSAStartup(version,&cli_wsadata);
  25. //客户端端口创建
  26. SOCKET m_hClientSocket;
  27. m_hClientSocket = socket(AF_INET,SOCK_STREAM, 0);
  28. //客户端向服务器发送连接请求
  29. SOCKADDR_IN m_addr1;
  30. m_addr1.sin_family = AF_INET;
  31. m_addr1.sin_addr.S_un.S_addr = inet_addr( “192.168.100.57”); //服务器的ip地址
  32. m_addr1.sin_port = htons( 10000); //服务器socket的端口号
  33. ret = connect(m_hClientSocket,(LPSOCKADDR)&m_addr1, sizeof(m_addr1)); //从客户端端口m_hClientSocket想服务器端口m_addr1发送连接请求
  34. //0xCD,0xCD,0xCD,0XCD. 因为DEBUG为每个字节初始化0xcd(204),你未正确取得对方IP,并且你的变量未初始化的结果。
  35. //开始使用accept和getpeername一直返回204.204.204.204的原因
  36. SOCKET com_Sock;
  37. SOCKADDR_IN addr_conn;
  38. int nSize = sizeof(addr_conn);
  39. //initialize the memory block via the memset function
  40. memset(( void *)&addr_conn, 0, sizeof(addr_conn));
  41. com_Sock = accept(m_hServerSocket, NULL, NULL); //从连接队列中取第一个连接进行通信
  42. //开始时候错误是因为把第三个参数写成了(int *)(sizeof(addr_conn)),所以不会报错但是取不到正确结果!!!
  43. //com_Sock = accept(m_hServerSocket,(SOCKADDR *)&addr_conn,&nSize); //or
  44. getpeername(com_Sock,(SOCKADDR *)&addr_conn,&nSize);
  45. char szPeerAddress[ 16];
  46. //Sets buffers to a specified character.
  47. memset(( void *)szPeerAddress, 0, sizeof(szPeerAddress));
  48. cout << szPeerAddress << “**************” << endl;
  49. //If no error occurs, inet_ntoa returns a character pointer to a static buffer
  50. //containing the text address in standard ".’’ notation
  51. strcpy(szPeerAddress,inet_ntoa(addr_conn.sin_addr));
  52. //Copy a string.the second parameter strSource Null-terminated source string
  53. cout << szPeerAddress << endl;
  54. //so remember that every time use the inet_ntoa, you must copy the result by yourself
  55. //or it will be covered by the other value
  56. addr_conn.sin_addr.S_un.S_addr = inet_addr( “192.168.111.2”);
  57. cout << inet_ntoa(addr_conn.sin_addr) << endl;
  58. cout << endl;
  59. }



你可能感兴趣的:(Internet)