Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <stdio.h>
- int main ( int argc, char *argv[] ) {
- WSADATA wsa;
- SOCKET sock;
- struct sockaddr_in sin;
- char szHost[80];
- char szBuf[250];
- WSAStartup( MAKEWORD( 2, 0 ), &wsa );
- // Create the socket
- sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
- if ( sock < 0 ) {
- printf( "Couldn't create socket...\n" );
- }
- memset( &sin, 0, sizeof( sin ) ); // Initialize to 0
- sin.sin_family = AF_INET; // Use AF_INET family
- sin.sin_port = htons( 5000 ); // Specify your port
- // Acquire the local computer IP address
- gethostname( szHost, sizeof( szHost ) );
- 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 ) );
- }
- // Connect the socket to the server
- if ( connect( sock, (SOCKADDR *)&sin, sizeof(sin) ) == SOCKET_ERROR ) {
- printf( "Connection failed with Socket Error: %i\n", WSAGetLastError() );
- }
- // Set the buffer data to the string
- strcpy( szBuf, "Hello this is a sample message!" );
- if ( send( sock, szBuf, sizeof(szBuf), 0 ) < 0 ) {
- printf( "Failed to send:\n%s\n\nWith Socket Error: %i\n", szBuf, WSAGetLastError() );
- } else {
- printf( "Sent:\n\n%s\n\n", szBuf );
- }
- // Require the user to press a key to exit
- system( "PAUSE" );
- return 0;
- }
Add Comment
Please, Sign In to add comment