Skip to content

Instantly share code, notes, and snippets.

@chelseakomlo
Last active September 13, 2015 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chelseakomlo/6b42d8e792f208e49eab to your computer and use it in GitHub Desktop.
Save chelseakomlo/6b42d8e792f208e49eab to your computer and use it in GitHub Desktop.
Socket programming
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <netinet/in.h>
int main(int argc, char *argv[]) {
// 1. determine a socket
int sockid;
sockid = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = 8080;
// 2. bind to that socket
int bind_status = bind(sockid, (struct sockaddr *)&server, sizeof(server));
printf("status %d", bind_status);
// 3. listen to that connection
int queue_limit = 50;
listen(sockid, queue_limit);
// 4. accept incoming connections
struct sockaddr client_addr;
socklen_t size = sizeof(client_addr);
int client_sockid = accept(sockid, (struct sockaddr *)&client_addr, &size);
return 0;
}
// a socket creates an endpoint for communication and returns a descriptor
// a socket's method signature is: socket(int domain, int type, int protocol);
// domain: selects the protocol family which should be used.
// type: specifies the semantics of communication (different for tcp and udp).
// protocol: specifies a protocol to be used with the socket.
#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int sockid;
// AF_INET: address format is host and port number
// SOCK_STREAM: this type provides sequenced, reliable, two-way connection based byte streams. (TCP connection)
sockid = socket(AF_INET, SOCK_STREAM, 0);
// connect(int socket, const struct sockaddr *address, socklen_t address_len);
// socket: the socket which the connection will be made
// address: the host which to connect to
struct sockaddr_in server;
// inet_addr() formats the server address from char to int
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
// use htons if byte order for the server is different than byte order for the client (big vs little endian)
server.sin_port = 8080;
int connect_status = connect(sockid, (struct sockaddr *)&server, sizeof(server));
printf("connect status %d", connect_status);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment