c - 为什么我在 netstat/ifconfig 中看不到服务器正在运行?

标签 c macos bash sockets

我在 unix 下用 c 编写服务器代码:

/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>

void error(const char *msg)
{
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[])
{
     int sockfd, newsockfd, portno;
     socklen_t clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        error("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
              error("ERROR on binding");
     listen(sockfd,5);
     clilen = sizeof(cli_addr);
     newsockfd = accept(sockfd, 
                 (struct sockaddr *) &cli_addr, 
                 &clilen);
     if (newsockfd < 0) 
          error("ERROR on accept");
     bzero(buffer,256);
     n = read(newsockfd,buffer,255);
     if (n < 0) error("ERROR reading from socket");
     printf("Here is the message: %s\n",buffer);
     n = write(newsockfd,"I got your message",18);
     if (n < 0) error("ERROR writing to socket");
     close(newsockfd);
     close(sockfd);
     return 0; 
}

我从 here 中获取了这段代码.

我在端口 8888 上运行代码 我的问题是当我在 bash 中运行这些命令时为什么看不到它:

netstat -a | grep 8888

ifconfig -a | grep 8888

但如果我这样做:

sudo cat /etc/services | grep 8888

我看到了。

我可以使用任何其他相关的 shell 命令来查看它吗?

最佳答案

如果端口 8888 列在您的 /etc/services 文件中,则 netstat 将用那里给出的名称替换端口号。这就是 grep 找不到它的原因。您可以使用 -n 标志关闭此功能:

$ netstat -a
...
tcp        0      0 *:ssh                   *:*                     LISTEN     
...
$ netstat -an
...
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
...

我通常使用 netstat -lpn -t tcp 只显示监听的 TCP 套接字;然后列表通常很短,可以用我的眼睛进行 grep。 -p 标志显示哪个程序正在监听,这通常很有帮助。

关于c - 为什么我在 netstat/ifconfig 中看不到服务器正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11061859/

相关文章:

c++ - 在 bash 中捕获线程转储

regex - 用于强密码的 Bash 正则表达式

c - 使用 webkitgtk+ 加载资源

c++ - 打开 cv 3.2.0 时出现苹果 mach-O 链接器 (id) 错误

仅当我在 glEnd 之后调用 glPopMatrix 时才会显示立方体(而不是相反)

html - Chrome Mac OSX 10.9.5 上的后台问题

c++ - in_addr 结构(IPv4 地址)的 Mac/Windows 不同格式

bash - 为什么 bash 只将第一个元素附加到数组

c++ - 邻域点删除的并行化

c - 我的代码在 C 编程中的顺序