© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu
Quick Links
Easy Studies

Home Lab Exercise Network Lab Exercise Programs Reading IP and port ID from command line and sending message to server▼


Reading IP and port ID from command line and sending message to server:

Algorithm Steps:

   Step 1: start

   Step 2: Read the any IP address and port ID and message on the command line

   Step3: Create a socket with address family AE_INET type  SOCK_STREAM and default protocol.

   Step 4: Initialize the socket and set its attribute set required port no.

   Step 5: Connect to server using connect () function to initiate the request.

   Step 6: If command line argument count equal to 4 then send the message to server.

   Step 7: Receive the string from the server and print it at the console.

   Step 8: stop.

C Program To Read IP and port ID from command line and send message to server

#include #include #include #include #include #include #include #include #define MAXBUF 1024 int main(int Count, char *Strings[]) { int sockfd, bytes_read; struct sockaddr_in dest; char buffer[MAXBUF]; /*---Make sure we have the right number of parameters---*/ if ( Count < 3 || Count > 4 ) { fprintf(stderr, "usage: %s []\n", Strings[0]); exit(0); } /*---Create socket for streaming---*/ if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { perror("Socket"); exit(errno); } /*---Initialize server address/port struct---*/ bzero(&dest, sizeof(dest)); dest.sin_family = AF_INET; if ( inet_addr(Strings[1], &dest.sin_addr.s_addr) == 0 ) { perror(Strings[1]); exit(errno); } dest.sin_port = htons(atoi(Strings[2])); /*---Connect to server---*/ if ( connect(sockfd, (struct sockaddr *)&dest, sizeof(dest)) != 0 ) { perror("Connect"); exit(errno); } /*---If there is a message to send server, send it with a '\n' (newline)---*/ if ( Count == 4 ) { sprintf(buffer, "%s\n", Strings[3]); send(sockfd, buffer, strlen(buffer), 0); } /*---While there's data, read and print it---*/ do { bzero(buffer, MAXBUF); bytes_read = recv(sockfd, buffer, MAXBUF, 0); if ( bytes_read > 0 ) printf("%s", buffer); } while ( bytes_read > 0 ); /*---Clean up---*/ close(sockfd); return 0; }

SAMPLE INPUT OUTPUT:

$ gcc test-port-client.c -o test.exe
$ test.exe 127.0.0.1 25
 connected

$ gcc test-port-client.c -o test.exe
$ test.exe 127.0.0.1 25 HAI
connected

 
SLogix Student Projects

⇓Student Projects⇓
⇑Student Projects⇑
bottom