|
| 1 | +/* |
| 2 | +Creating the TCP Client workflow in this program using C. |
| 3 | +
|
| 4 | + * Title : TCP client |
| 5 | + * Name : Aditya Pratap Singh Rajput |
| 6 | + * Subject : Network Protocols And Programming |
| 7 | +
|
| 8 | +Note : please consider the TYPOS in comments. |
| 9 | +Thanks. |
| 10 | +*/ |
| 11 | +//adding includes |
| 12 | +#include <stdio.h> |
| 13 | +#include <stdlib.h> |
| 14 | +//for socket and related functions |
| 15 | +#include <sys/types.h> |
| 16 | +#include <sys/socket.h> |
| 17 | +//for including structures which will store information needed |
| 18 | +#include <netinet/in.h> |
| 19 | + |
| 20 | +#include <unistd.h> |
| 21 | +//main functions |
| 22 | +int main(){ |
| 23 | + //creating a socket |
| 24 | + int network_socket; |
| 25 | + //calling socket function and storing the result in the variable |
| 26 | + //socket(domainOfTheSocket,TypeOfTheSocket,FlagForProtocol{0 for default protocol i.e, TCP}) |
| 27 | + //AF_INET = constant defined in the header file for us |
| 28 | + //TCP vs UDP --- SOCK_STRAM for TCP |
| 29 | + // flag 0 for TCP (default protocol) |
| 30 | + network_socket = socket(AF_INET,SOCK_STREAM,0); |
| 31 | + //creating network connection |
| 32 | + //in order to connect to the other side of the socket we need to declare connect |
| 33 | + //with specifying address where we want to connect to |
| 34 | + //already defined struct sockaddr_in |
| 35 | + struct sockaddr_in server_address; |
| 36 | + //what type of address we are woking with |
| 37 | + server_address.sin_family = AF_INET; |
| 38 | +//for taking the port number and htons converts the port # to the appropriate data type we want to write |
| 39 | +//to specifying the port |
| 40 | +//htons : conversion functions |
| 41 | + server_address.sin_port = htons(9002); |
| 42 | + //structure within structure A.B.c |
| 43 | + server_address.sin_addr.s_addr = INADDR_ANY;//INADDR_ANY is for connection with 0000 |
| 44 | +//connect returns us a response that connection is establlised or not |
| 45 | +int connect_status = connect(network_socket,(struct sockaddr *) &server_address, sizeof(server_address)); |
| 46 | +//check for the error with the connection |
| 47 | +if (connect_status == -1){ |
| 48 | + printf("There was an error making a connection to socket\n" ); |
| 49 | +} |
| 50 | +//recieve data from the server |
| 51 | +char server_response[256]; |
| 52 | +//recieve the data from the server |
| 53 | +recv(network_socket,&server_response,sizeof(server_response),0); |
| 54 | +//recieved data from the server successfully then printing the data obtained from the server |
| 55 | + |
| 56 | +printf("Ther server sent the data : %s",server_response); |
| 57 | +//closing the socket |
| 58 | +close(network_socket); |
| 59 | + return 0; |
| 60 | +} |
0 commit comments