我从Andy Tanenbaum的书中得到了这段代码。我正在尝试运行它。它编译并等待连接。但是当我输入localhost:886
时,我在浏览器或终端中看不到任何效果。 (它应该按照代码回显一个新的连接字符串)。Linux服务器编程
#define SERVER_PORT 886 /* The port at which the server listens */
#define BUF_SIZE 64032 /* The size of buffer for request and response */
#define QUEUE_SIZE 10 /* Block transfer size */
int main (int argc, char* argv[]) {
int sock = 0, bnd = 0, lst = 0, fd = 0, sa = 0, bytes = 0, on = 1, conn_count = 0;
char buf[BUF_SIZE];
struct sockaddr_in channel; /* IP address holder */
/* The address structure that binds with the socket */
memset (&channel, 0, sizeof(channel));
channel.sin_family = AF_INET;
channel.sin_addr.s_addr = htonl (INADDR_ANY);
channel.sin_port = htons (SERVER_PORT);
/* Parital opening of the socket, while waiting for connection */
sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Creates a new socket */
if (sock < 0)
printf ("Partial opening of the socket failed! Error: %d", sock);
setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));
bnd = bind (sock, (struct sockaddr *) &channel, sizeof(channel));
if (bnd < 0)
printf ("Binding failure! Error: %d", bnd);
lst = listen (sock, QUEUE_SIZE);
if (lst < 0)
printf ("Unable to listen on the socket! Error: %d", lst);
/* The socket has been set-up. Wait for the connection and process it. */
while (1) {
conn_count += 1;
printf ("Received connection: %d", conn_count);
sa = accept (sock, 0, 0);
if (sa < 0)
puts ("Unable to accept the socket opened for connection.");
read (sa, buf, BUF_SIZE);
puts (buf); /* Output the string to the screen */
close (sa);
}
}
尝试'远程登录本地主机的所有端口:886'在命令行上。 –
您可以通过'netstat'确认您的程序是否实际正在侦听适当的端口。 –
'netstat -tlnp' – Flavius