Skip to content

Instantly share code, notes, and snippets.

@ooharak
Created December 11, 2012 06:39
Show Gist options
  • Save ooharak/4256378 to your computer and use it in GitHub Desktop.
Save ooharak/4256378 to your computer and use it in GitHub Desktop.
An attempt to establish a TCP/IP connection to a host (C socket)
/* written by ooharak 2012. */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define HOST_IP "8.8.8.8"
#define HOST_PORT 80
#define TIMEOUT_MILLIS 1234
#define maybe(s) (errno=0,_maybe(#s, s))
int _maybe(char *s, int r);
int
_maybe(char *s, int r)
{
if (r == -1) {
perror(s);
exit(1);
}
return r;
}
int
main(int argc, char *argv[])
{
int timeout = TIMEOUT_MILLIS;
int fd;
int flag;
struct sockaddr_in addr = { AF_INET, htons(HOST_PORT), inet_addr(HOST_IP) };
int pollresult = -1;
struct pollfd aPollfd;
aPollfd.events = POLLOUT;
fd = maybe(socket(PF_INET, SOCK_STREAM, 0));
flag = maybe(fcntl(fd, F_GETFL));
maybe(fcntl(fd, F_SETFL, flag|O_NONBLOCK));
if (-1 == connect(fd, (struct sockaddr *) &addr, sizeof(addr))) {
if (EINPROGRESS == errno) {
//ok
} else {
perror("connect");
exit(4);
}
} else {
puts("connection succeeded before polling");
}
aPollfd.fd = fd;
pollresult = maybe(poll(&aPollfd, 1, timeout));
if (0 == pollresult) {
puts("timeout");
} else {
puts("success");
}
flag = maybe(fcntl(fd, F_GETFL));
maybe(fcntl(fd, F_SETFL, flag|O_NONBLOCK));
maybe(shutdown(fd, SHUT_RDWR));
maybe(close(fd));
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment