Guest User

Untitled

a guest
Jul 16th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. #include <windows.h>
  2. #include <stdio.h>
  3.  
  4. int main ( int argc, char *argv[] ) {
  5. WSADATA wsa;
  6. SOCKET sock;
  7.  
  8. struct sockaddr_in sin;
  9. char szHost[80];
  10. char szBuf[250];
  11.  
  12. WSAStartup( MAKEWORD( 2, 0 ), &wsa );
  13.  
  14. // Create the socket
  15. sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
  16.  
  17. if ( sock < 0 ) {
  18. printf( "Couldn't create socket...\n" );
  19. }
  20.  
  21. memset( &sin, 0, sizeof( sin ) ); // Initialize to 0
  22. sin.sin_family = AF_INET; // Use AF_INET family
  23. sin.sin_port = htons( 5000 ); // Specify your port
  24.  
  25. // Acquire the local computer IP address
  26. gethostname( szHost, sizeof( szHost ) );
  27. struct hostent *sHost = gethostbyname( szHost );
  28. for ( int i = 0; sHost->h_addr_list[i] != 0; i++ ) {
  29. struct in_addr addr;
  30. memcpy( &addr, sHost->h_addr_list[i], sizeof( struct in_addr ) );
  31. printf( "Found local address: %s\n", inet_ntoa( addr ) );
  32. sin.sin_addr.s_addr = inet_addr( inet_ntoa( addr ) );
  33. }
  34.  
  35. // Connect the socket to the server
  36. if ( connect( sock, (SOCKADDR *)&sin, sizeof(sin) ) == SOCKET_ERROR ) {
  37. printf( "Connection failed with Socket Error: %i\n", WSAGetLastError() );
  38. }
  39.  
  40. // Set the buffer data to the string
  41. strcpy( szBuf, "Hello this is a sample message!" );
  42. if ( send( sock, szBuf, sizeof(szBuf), 0 ) < 0 ) {
  43. printf( "Failed to send:\n%s\n\nWith Socket Error: %i\n", szBuf, WSAGetLastError() );
  44. } else {
  45. printf( "Sent:\n\n%s\n\n", szBuf );
  46. }
  47.  
  48. // Require the user to press a key to exit
  49. system( "PAUSE" );
  50. return 0;
  51. }
Add Comment
Please, Sign In to add comment