1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #pragma comment(lib, "ws2_32.lib")
#include <winsock2.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
using namespace std;
int main()
{
cout << "Starting up TCP server\r\n";
SOCKET server;
WSADATA wsaData;
sockaddr_in local;
int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret!=0)
{
return 0;
}
//Now we populate the sockaddr_in structure
local.sin_family=AF_INET; //Address family
local.sin_addr.s_addr=INADDR_ANY; //Wild card IP address
local.sin_port=htons((u_short)4148); //port to use
//the socket function creates our SOCKET
server=socket(AF_INET,SOCK_STREAM,0);
//If the socket() function fails we exit
if(server==INVALID_SOCKET)
{
return 0;
}
if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
{
return 0;
}
//listen instructs the socket to listen for incoming
//connections from clients. The second arg is the backlog
if(listen(server,10)!=0)
{
return 0;
}
//we will need variables to hold the client socket.
//thus we declare them here.
SOCKET client;
sockaddr_in from;
int fromlen=sizeof(from);
while(true)//we are looping endlessly
{
char temp[512];
// char buff[512];
//accept() will accept an incoming
//client connection
client=accept(server,(struct sockaddr*)&from,&fromlen);
sprintf(temp,"Your IP is %s\r\n\r\n",inet_ntoa(from.sin_addr));
//we simply send this string to the client
send(client,temp,strlen(temp),0);
sprintf(temp," %s is your IP\r\n\r\n",inet_ntoa(from.sin_addr));
send(client,temp,strlen(temp),0);
cout << "Connection from " << inet_ntoa(from.sin_addr) <<"\r\n";
//close the client socket
closesocket(client);
}
//closesocket() closes the socket and releases the socket descriptor
closesocket(server);
//originally this function probably had some use
//currently this is just for backward compatibility
//but it is safer to call it as I still believe some
//implementations use this to terminate use of WS2_32.DLL
WSACleanup();
return 0;
} |
Partager