Skip to content

Instantly share code, notes, and snippets.

@AjayKrP
Created September 23, 2017 04:40
Show Gist options
  • Save AjayKrP/7504391fc3cf1157e1f637e3494c028c to your computer and use it in GitHub Desktop.
Save AjayKrP/7504391fc3cf1157e1f637e3494c028c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char *argv[]) {
int sockfd;//socket file descriptor
ssize_t n; // for storing returned value from client
uint16_t portno;
struct sockaddr_in serv_addr;//contains sin_family, sin_port, struct in_addr sin_addr, sin_zero[8]
struct hostent *server;
/*
struct hostent {
char *h_name; // official name of host
char **h_aliases; // alias list
int h_addrtype; // host address type
int h_length; // length of address
char **h_addr_list; // list of addresses
};
*/
char buffer[256]; // for storing message returned from client side
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = (uint16_t)atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);//this returned your computer host name
if (server == NULL) { // in case you entered wrong host
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));//The bzero() function shall place n zero-valued bytes in the area pointed to by s.
serv_addr.sin_family = AF_INET;
bcopy(server->h_addr, //official name of host
(char *)&serv_addr.sin_addr.s_addr,//contains ip address
(size_t)server->h_length);//length of address
serv_addr.sin_port = htons(portno);//function converts the unsigned short integer hostshort from host byte order to network byte order.
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment