Build a program in C that exchanges data over the network.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> // close() #include <arpa/inet.h> // inet_addr(), htons() #include <netdb.h> // gethostbyname() #include <sys/socket.h> // socket(), connect(), send(), recv()
winsock2.h.#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #define BUF_SIZE 4096 int main(void) { const char *host = "example.com"; int port = 80; // ===== 1. Resolve hostname to IP address ===== struct hostent *server = gethostbyname(host); if (server == NULL) { fprintf(stderr, "Host lookup failed\n"); return 1; } // ===== 2. Create a socket ===== int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); return 1; } // ===== 3. Set up server address ===== struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); // port in network byte order memcpy(&addr.sin_addr.s_addr, server->h_addr, server->h_length); // ===== 4. Connect to server ===== if (connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("connect"); close(sockfd); return 1; } printf("Connected: %s:%d\n\n", host, port); // ===== 5. Send HTTP request ===== char request[BUF_SIZE]; snprintf(request, BUF_SIZE, "GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", host); send(sockfd, request, strlen(request), 0); // ===== 6. Receive and print response ===== char buf[BUF_SIZE]; int n; while ((n = recv(sockfd, buf, BUF_SIZE - 1, 0)) > 0) { buf[n] = '\0'; printf("%s", buf); } // ===== 7. Disconnect ===== close(sockfd); printf("\n\nConnection closed\n"); return 0; }
| Function | Purpose | Arguments | Returns |
|---|---|---|---|
socket() | Create a socket | AF_INET, SOCK_STREAM, 0 | socket fd (int) |
gethostbyname() | Hostname β IP | "example.com" | pointer to hostent |
connect() | Connect to server | sockfd, addr, addrlen | 0 = ok, -1 = fail |
send() | Send data | sockfd, buf, len, flags | bytes sent |
recv() | Receive data | sockfd, buf, len, flags | bytes received (0 = closed) |
close() | Close socket | sockfd | 0 = ok |
htons() | Host-to-network short (ports) | port number | converted port |
struct sockaddr_in { short sin_family; // address family (AF_INET) unsigned short sin_port; // port (use htons() to convert) struct in_addr sin_addr; // IP address char sin_zero[8]; // padding };
int connect_to_server(const char *host, int port), returning the socket fd. Return -1 on error.\r\n; recv_line reads up to \r\n../http_client example.com 80, taking host and port from argv. See the argc/argv lesson.