Created
June 11, 2012 14:12
-
-
Save bnoordhuis/2910263 to your computer and use it in GitHub Desktop.
Create an AF_INET socket and connect() it to itself
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
/* | |
* Copyright (c) 2012, Ben Noordhuis <info@bnoordhuis.nl> | |
* | |
* Permission to use, copy, modify, and/or distribute this software for any | |
* purpose with or without fee is hereby granted, provided that the above | |
* copyright notice and this permission notice appear in all copies. | |
* | |
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | |
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | |
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | |
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | |
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | |
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | |
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
#define E(expr) \ | |
do { \ | |
errno = 0; \ | |
do { expr; } while (0); \ | |
if (errno) perror(#expr), abort(); \ | |
} \ | |
while (0) | |
int main(void) | |
{ | |
struct sockaddr_in sin; | |
char buf[32]; | |
int on; | |
int fd; | |
memset(&sin, 0, sizeof(sin)); | |
sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); | |
sin.sin_family = AF_INET; | |
sin.sin_port = htons(1337); | |
on = 1; | |
E(fd = socket(AF_INET, SOCK_STREAM, 0)); | |
E(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))); | |
E(bind(fd, (struct sockaddr *) &sin, sizeof(sin))); | |
// E(listen(fd, 32)); // should make connect() fail with EISCONN | |
E(connect(fd, (struct sockaddr *) &sin, sizeof(sin))); | |
// E(listen(fd, 32)); // should fail with EOPNOTSUPP | |
E(write(fd, "test", 4)); | |
E(read(fd, buf, sizeof(buf))); // reads "test" | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment