Created
June 21, 2011 11:09
-
-
Save grapswiz/1037635 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <string.h> | |
#include <netdb.h> | |
#include <arpa/inet.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
struct servent * getService(char *, char *); | |
struct hostent * getHost(char *); | |
int getSocket(int, int, int); | |
int main(int argc, char *argv[]) { | |
struct servent *servinfo; | |
struct hostent *servhost; | |
char *port = "ftp"; | |
char *host_name; | |
struct sockaddr_in server; | |
int sock; | |
// プログラムの引数をhostname,サービス名とする | |
if (sizeof(argv) < 2) { | |
printf("rterm host_name {service_name}"); | |
exit(0); | |
} | |
host_name = argv[1]; | |
printf("gethostname: OK\n"); | |
if (argv[2] != NULL) { | |
port = argv[2]; | |
} | |
servinfo = getService(port, "tcp"); | |
servhost = getHost(host_name); | |
sock = getSocket(AF_INET, SOCK_STREAM, 0); | |
memset((char *)&server, 0, sizeof(server)); | |
server.sin_family = AF_INET; | |
server.sin_port = htons(servinfo->s_port); | |
memcpy((char *)&server.sin_addr, servhost->h_addr, servhost->h_length); | |
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1) { | |
perror("connect"); | |
exit(0); | |
} | |
printf("connect: OK"); | |
return 0; | |
} | |
struct servent * getService(char *port, char *proto) { | |
struct servent *a; | |
a = getservbyname(port, proto); | |
if (a == NULL) { | |
perror("getservbyname"); | |
exit(0); | |
} | |
printf("getservbyname: OK\n"); | |
return a; | |
} | |
struct hostent * getHost(char *host_name) { | |
struct hostent *a; | |
unsigned long addr; | |
a = gethostbyname(host_name); | |
if (a == NULL) { | |
addr = inet_addr(host_name); | |
a = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); | |
if (a == NULL) { | |
perror("gethostbyaddr"); | |
exit(0); | |
} | |
} | |
printf("gethostname: OK\n"); | |
return a; | |
} | |
int getSocket(int domain, int type, int proto) { | |
int a; | |
a = socket(domain, type, proto); | |
if (a < 0) { | |
perror("socket"); | |
exit(0); | |
} | |
printf("socket: OK\n"); | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment