Last active
November 18, 2018 08:46
-
-
Save hirokuma/d785a85940ba0bb806141984780b4424 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> //printf | |
#include <string.h> //memset | |
#include <unistd.h> //close | |
#include <sys/socket.h> //socket | |
#include <arpa/inet.h> //inet | |
#include <sys/types.h> //getaddrinfo | |
#include <netdb.h> //getaddrinfo | |
static int tcp_connect(const char *pAddr, const char *pService) | |
{ | |
struct addrinfo hints; | |
struct addrinfo *ainfo = NULL; | |
int sock = -1; | |
//IPアドレス取得 | |
memset(&hints, 0, sizeof(hints)); | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_family = AF_INET; | |
int ret = getaddrinfo(pAddr, pService, &hints, &ainfo); | |
if (ret == 0) { | |
struct addrinfo *rp; | |
for (rp = ainfo; rp != NULL; rp = rp->ai_next) { | |
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
if (sock < 0) { | |
fprintf(stderr, "fail: sock\n"); | |
goto ERR_EXIT; | |
} | |
struct sockaddr_in *in = (struct sockaddr_in *)rp->ai_addr; | |
fprintf(stderr, "addr : %s\n", inet_ntoa(in->sin_addr)); | |
ret = connect(sock, rp->ai_addr, rp->ai_addrlen); | |
if (ret == 0) { | |
//接続OK | |
fprintf(stderr, "connected\n"); | |
break; | |
} | |
} | |
if (rp == NULL) { | |
goto ERR_EXIT; | |
} | |
} else { | |
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); | |
} | |
ERR_EXIT: | |
freeaddrinfo(ainfo); | |
return sock; | |
} | |
int main(void) | |
{ | |
int sock = tcp_connect("www.yahoo.co.jp", "443"); | |
printf("socket=%d\n", sock); | |
close(sock); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment