Skip to content

Instantly share code, notes, and snippets.

@micromaomao
Created July 15, 2015 11:00
Show Gist options
  • Save micromaomao/922ae47d7813834f67d8 to your computer and use it in GitHub Desktop.
Save micromaomao/922ae47d7813834f67d8 to your computer and use it in GitHub Desktop.
Linux socket test
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define BUFLEN 10
int main( int argc, char **argv )
{
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_UNSPEC;
addrinfo* res;
int ret = getaddrinfo("::1", "2333", const_cast<const addrinfo*>(&hints), &res);
if(ret != 0)
return ret;
int sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(sockfd == -1)
return errno;
ret = connect(sockfd, const_cast<const sockaddr*>(res->ai_addr), res->ai_addrlen);
if(ret != 0)
return errno;
freeaddrinfo(res);
while(1) {
void* buf = new char[BUFLEN];
ssize_t rtt = read(0, buf, BUFLEN);
if (rtt == -1 || rtt == 0) {
int ern = errno;
close(sockfd);
return ern;
}
ssize_t rtc = write(sockfd, buf, rtt);
if(rtc == -1) {
int ernn = errno;
close(sockfd);
return ernn;
}
}
}
nc -l ::1 2333
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment