Created
August 31, 2014 21:47
-
-
Save brianherman/4d393c1b69c2bd5c1f1f to your computer and use it in GitHub Desktop.
385
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <netdb.h> | |
#include <string.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
int main(int argc, char *argv[]) | |
{ | |
int sockfd, portno, n; | |
struct sockaddr_in serv_addr; | |
struct hostent *server; | |
char buffer[256]; | |
if (argc < 2) { | |
fprintf(stderr,"%s portnumber \n", argv[0]); | |
exit(0); | |
} | |
portno = atoi(argv[1]); | |
printf("using port: %d", portno); | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd < 0){ | |
perror("ERROR opening socket"); | |
exit(-1); | |
} | |
server = gethostbyname("127.0.0.1"); | |
if (server == NULL) { | |
fprintf(stderr,"ERROR, no such host\n"); | |
exit(0); | |
} | |
memset( &serv_addr,0, sizeof(serv_addr)); | |
serv_addr.sin_family = AF_INET; | |
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length); | |
serv_addr.sin_port = htons(portno); | |
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) { | |
perror("ERROR connecting"); | |
exit(-1); | |
} | |
n = write(sockfd,"hello",strlen("hello")); | |
if (n < 0) { | |
perror("ERROR writing to socket"); | |
exit(-1); | |
} | |
n = read(sockfd,buffer,255); | |
if (n < 0) { | |
perror("ERROR reading from socket"); | |
exit(-1); | |
} | |
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