开发者社区> 问答> 正文

c 语言 socketERR_CONNECTION_REFUSED

下面的代码无法在浏览器下访问,什么原因?:
编译运行后应该输出html代码
localhost:8001


#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
void doprocessing (int sock);

int main( int argc, char *argv[] ) {
   int sockfd, newsockfd, portno, clilen;
   char buffer[256];
   struct sockaddr_in serv_addr, cli_addr;
   int n, pid;

   /* First call to socket() function */
   sockfd = socket(AF_INET, SOCK_STREAM, 0);

   if (sockfd < 0) {
      perror("ERROR opening socket");
      exit(1);
   }

   /* Initialize socket structure */
   bzero((char *) &serv_addr, sizeof(serv_addr));
   portno = 8001;

   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = INADDR_ANY;
   serv_addr.sin_port = htons(portno);

   //printf("FAMILY : %s,%s",AF_INET,INADDR_ANY);

   /* Now bind the host address using bind() call.*/
   if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
      perror("ERROR on binding");
      exit(1);
   }

   /* Now start listening for the clients, here
      * process will go in sleep mode and will wait
      * for the incoming connection
   */

   listen(sockfd,5);
   clilen = sizeof(cli_addr);

   //while (1) {
      newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

      if (newsockfd < 0) {
         perror("ERROR on accept");
         exit(1);
      }
     doprocessing(newsockfd);
   //} /* end of while */
}

void doprocessing (int sock) {
   int n;
   char buffer[256];
   bzero(buffer,256);
   n = read(sock,buffer,255);

   if (n < 0) {
      perror("ERROR reading from socket");
      exit(1);
   }

    printf("HTTP/1.1 200 Okay\r\nContent-Type: text/html; charset=ISO-8859-4 \r\n\r\n<h1>Hello, client! Welcome to the Virtual Machine Web..</h1>");
exit(1);

}

展开
收起
杨冬芳 2016-05-30 11:35:54 2572 0
1 条回答
写回答
取消 提交回答
  • printf("HTTP/1.1 200 OkayrnContent-Type: text/html; charset=ISO-8859-4 rnrn

    Hello, client! Welcome to the Virtual Machine Web..

    "); 这句话的意思是往你的终端打印内容,而不是往客户端的链接中输出内容,改成:

    char buf[] = "HTTP/1.1 200 OkayrnContent-Type: text/html; charset=ISO-8859-4 rnrn

    Hello, client! Welcome to the Virtual Machine Web..

    ";
    write(sock, buf, sizeof(buf));
    

    就可以了

    2019-07-17 19:20:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载