Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ////////////////////////////////////////////////////////////////////////////////////////
- // A simple example of opening a AF_INET family TCP socket and receiving data over it
- // This code will compile in a Win32 Console application in VS if you include:
- // Include: wsock32.lib
- // (project -> properties -> linker -> input -> additional dependencies
- ////////////////////////////////////////////////////////////////////////////////////////
- #include <windows.h>
- #include <stdio.h>
- int main( int argc, char* argv[] ) {
- ## Data Declarations
- WSADATA wsa; // WSA Socket Data
- SOCKET sock; // The Socket
- SOCKADDR_IN sin; // The Socket Address
- char szHost[80]; // A buffer for the hostname
- char szBuf[250]; // A buffer for the received data
- ## Init
- // Initialize Windows Sockets in the app
- WSAStartup( MAKEWORD(2, 0), &wsa ); // Returns error code, 0 = no error
- // Acquire the local computers host name
- gethostname( szHost, sizeof( szHost ) ); // Also returns 0 if successful
- // Acquire the local computer IP address
- struct hostent *sHost = gethostbyname( szHost );
- for ( int i = 0; sHost->h_addr_list[i] != 0; i++ ) {
- struct in_addr addr;
- memcpy( &addr, sHost->h_addr_list[i], sizeof( struct in_addr ) );
- printf( "Found local address: %s\n", inet_ntoa( addr ) );
- sin.sin_addr.s_addr = inet_addr( inet_ntoa( addr ) );
- }
- // Set address family... AF_INET can be connection-oriented (TCP) or connectionless (UDP)
- sin.sin_family = AF_INET;
- sin.sin_port = htons( 5000 ); // The port number you want to use for the connection
- // Tell windows to create a TCP socket
- sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
- // Make sure it worked
- if ( sock == INVALID_SOCKET ) {
- printf( "Socket failed to create.\n" );
- }
- ## Bind
- // Bind the socket to the address
- if ( bind( sock, (struct sockaddr *)&sin, sizeof(SOCKADDR_IN) ) < 0 ) {
- printf( "Bind failed...\n" );
- }
- ## Listen
- // Now listen for incoming connections on the socket
- // The second parameter is how many connections this socket will listen for and accept
- // We set it to 1 here to only allow one incoming connection request
- if ( listen( sock, 1 ) < 0 ) {
- printf( "Listen failed...\n" );
- }
- printf( "Socket init... OK\nWaiting for connection... " );
- ## Accept -- Blocks
- // This accepts the incoming connection, and will block indefinitely waiting for it
- sock = accept( sock, NULL, NULL );
- ## Receive data
- printf( "Connection established!\n" );
- memset( szBuf, 0, sizeof(szBuf) );
- // Receive data from the connection
- if ( recv( sock, szBuf, sizeof(szBuf), 0 ) >= 0 ) {
- // Print the data to the screen
- printf( "The server received:\n\n%s\n\n", szBuf );
- } else {
- printf( "Recv failed with Socket Error: %i\n", WSAGetLastError() );
- }
- // Make the user press any key to exit
- system("PAUSE");
- return 0;
- }
Add Comment
Please, Sign In to add comment