我從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