#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <netdb.h>
#include <pthread.h>
#include <sys/resource.h>
#include <sys/uio.h>
#define SA struct sockaddr
#define err(msg) perror(msg)
static int tcp_listen(const char *ip, int port)
{
struct sockaddr_in addr;
int fd;
int on = 1;
if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
err("socket");
goto out;
}
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
memset(&addr, '\0', sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &addr.sin_addr) < 0) {
err("inet_pton");
goto err;
}
if (bind(fd, (SA *)&addr, sizeof(addr)) == -1) {
err("bind");
goto err;
}
if (listen(fd, 10) == -1) {
err("listen");
goto err;
}
return fd;
err:
close(fd);
out:
return -1;
}
static void handle_conn(int fd)
{
struct msghdr msg;
struct iovec iov[2], *piov;
char buf0[5], buf1[10];
ssize_t len;
int i, dlen;
memset(buf0, '\0', sizeof(buf0));
memset(buf1, '\0', sizeof(buf1));
iov[0].iov_base = buf0;
iov[0].iov_len = 5;
iov[1].iov_base = buf1;
iov[1].iov_len = 10;
memset(&msg, '\0', sizeof(msg));
msg.msg_iov = iov;
msg.msg_iovlen = 2;
if ((len = recvmsg(fd, &msg, 0)) == -1) {
err("recvmsg");
return;
}
piov = iov;
while (len > 0) {
if (len <= piov->iov_len)
dlen = len;
else
dlen = piov->iov_len;
printf("dlen = %d\n", dlen);
if (write(STDOUT_FILENO, piov->iov_base, dlen) == -1) {
err("write");
break;
}
piov++; /* f: pointer to next iov */
len -= dlen;
}
}
int main(void)
{
int fd;
if ((fd = tcp_listen("0.0.0.0", 8888)) == -1) {
err("tcp_listen");
goto out;
}
while (1) {
int connfd = accept(fd, NULL, NULL);
if (connfd == -1) {
err("accept");
break;
}
handle_conn(connfd);
close(connfd);
}
close(fd);
return 0;
out:
return -1;
}
|