This code has no actual functionality, just to get the IP address of the other end of the connection
#include <iostream> #include <winsock.h> #include <stdio.h> #pragma comment (lib, "Wsock32") using name
Space Std;
void Main () {int ret = 0;
Wsadata Wsadata;
WORD Version = Makeword (2,0);
ret = WSAStartup (version,&wsadata);
Server port create SOCKET m_hserversocket;
M_hserversocket = socket (af_inet,sock_stream,0);
Server port binding sockaddr_in m_addr;
m_addr.sin_family = af_inet; M_addr.sin_addr. S_un.
S_ADDR = inaddr_any;//If the server is a single NIC, then this is the IP address of the network card, if it is a multiple network card, then any one of the IP address M_addr.sin_port = htons (10000);
ret = bind (M_hserversocket, (LPSOCKADDR) &m_addr,sizeof (M_ADDR));
Server ports start LISTENING ret = listen (m_hserversocket,10);//The second parameter specifies the maximum number of connections to apply Wsadata cli_wsadata;
ret = WSAStartup (version,&cli_wsadata);
Client port create SOCKET M_hclientsocket;
M_hclientsocket = socket (af_inet,sock_stream,0);
The client sends a connection request to the server sockaddr_in M_ADDR1;
m_addr1.sin_family = af_inet; M_addr1.sin_addr. S_un. S_ADDR = inet_addr ("192.168.100.57");/server IP address M_addr1.sin_port = htons (10000);//Server SocKet's port number is ret = connect (M_hclientsocket, (LPSOCKADDR) &m_addr1,sizeof (M_ADDR1));//M_hclientsocket from client port to server port m_ ADDR1 Send connection request//0XCD,0XCD,0XCD,0XCD.
Because debug initializes 0xcd (204) for each byte, you do not get the other IP correctly, and your variables are uninitialized.
Start using accept and getpeername to return 204.204.204.204 to the cause of SOCKET com_sock;
Sockaddr_in Addr_conn;
int nsize = sizeof (Addr_conn);
Initialize the memory block via the Memset function memset ((void *) &addr_conn,0,sizeof (addr_conn)); Com_sock = Accept (m_hserversocket,null,null);
The first connection from the connection queue is communicated//At first the error is because the third argument is written (int *) (sizeof (addr_conn)), so no error is given but the correct result is not obtained ... Com_sock = Accept (M_hserversocket, (SOCKADDR *) &addr_conn,&nsize);
or Getpeername (Com_sock, (SOCKADDR *) &addr_conn,&nsize);
Char szpeeraddress[16];
Sets buffers to a specified character.
memset ((void *) szpeeraddress,0,sizeof (szpeeraddress));
cout << szpeeraddress << "**************" <<endl; If No error occurs, INET_NTOA returns a character pointer to a static buffer//containing The text address in standard "." Notation strcpy (Szpeeraddress,inet_ntoa (ADDR_CONN.SIN_ADDR));
Copy a string.the second parameter strsource null-terminated source string cout << szpeeraddress << Endl; So remember this every time use of the Inet_ntoa, you must copy of the result by yourself//or it'll be covered by the oth ER value addr_conn.sin_addr. S_un.
S_ADDR = inet_addr ("192.168.111.2");
cout << Inet_ntoa (addr_conn.sin_addr) << Endl;
cout << Endl; }