我从Andy Tanenbaum的书里得到了这个代码。我正在试着运行它。它编译并等待连接。但是当我输入localhost:886时,我在浏览器或终端中都看不到任何效果。(它应该根据代码回显一个新的连接字符串)。
#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);
}
}发布于 2011-08-18 23:55:10
您是否以sudo/root身份运行此应用程序?您的bind()可能会失败,因为它正在使用特权端口。
来自评论的更新:
特权端口是1024以下的所有端口。
发布于 2011-08-18 23:44:36
尝试将换行符'\n‘放在您的
printf ("Received connection: %d\n", conn_count); 线路。
否则,不会直接刷新stdout,您将什么也看不到。
发布于 2011-08-18 23:49:32
与其使用printf()和stdout,不如尝试将所有输出更改为没有缓冲的fprintf()和stderr……我也会对错误消息执行同样的操作,以便它们在被调用时立即输出,而不是由stdout缓冲。
最后,如果您想了解错误消息的含义,可以使用带有错误号的strerror()。所以你可以这样做:
if (bnd < 0)
{
fprintf(stderr, "Binding failure! Error: %s", strerror(bnd));
exit(1);
}确保对于strerror(),您还在代码模块开头的某个位置执行了include<string.h>。
https://stackoverflow.com/questions/7110059
复制相似问题