簡體   English   中英

C 中的套接字編程,服務器代碼出錯

[英]Socket Programming in C, server code with an error

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[]){
    // established the socket
    char inputBuffer[256] = {};
    char message[] = {"Hi this is the server.\n"};
    int sockfd = 0;
    int forClientSocketfd = 0;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1) printf("Fail to create the socket.");

    // socket connection
    struct sockaddr_in serverInfo, clientInfo;
    int addrlen = sizeof(clientInfo);
    bzero(&serverInfo, sizeof(serverInfo));

    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr.s_addr = INADDR_ANY;
    serverInfo.sin_port = htron(10024);
    bind(sockfd, (struct sockaddr *) &serverInfo, sizeof(serverInfo));
    listen(sockfd, 5);

    while(1){
        forClientSocketfd = accept(sockfd, (struct sockaddr*) &clientInfo, &addrlen);
        send(forClientSocketfd, message, sizeof(message), 0);
        recv(forClientSocketfd, inputBuffer, sizeof(inputBuffer), 0);
        printf("Received from client: %s\n", inputBuffer);
    }

    return 0;
}

這是我從網上看到的socket編程的代碼。 當我編譯它時,它會拋出如下錯誤消息。 不知道發生了什么,即使通過互聯網搜索。 ps 客戶端正常運行。

在此處輸入圖像描述

你在第 24 行有錯字,應該是htons而不是htron

噸()

htons function 采用主機字節順序的 16 位數字,並返回 TCP/IP 網絡(AF_INET 或 AF_INET6 地址系列)中使用的網絡字節順序的 16 位數字。 htons function 可用於將主機字節順序中的 IP 端口號轉換為網絡字節順序中的 IP 端口號

還將 stdio header 文件添加到您的代碼中以刪除其他警告,這是最終更正的代碼,沒有警告或錯誤。

#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    // established the socket
    char inputBuffer[256] = {};
    char message[] = {"Hi this is the server.\n"};
    int sockfd = 0;
    int forClientSocketfd = 0;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
        printf("Fail to create the socket.");

    // socket connection
    struct sockaddr_in serverInfo, clientInfo;
    int addrlen = sizeof(clientInfo);
    bzero(&serverInfo, sizeof(serverInfo));

    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr.s_addr = INADDR_ANY;
    serverInfo.sin_port = htons(10024);
    bind(sockfd, (struct sockaddr *)&serverInfo, sizeof(serverInfo));
    listen(sockfd, 5);

    while (1)
    {
        forClientSocketfd = accept(sockfd, (struct sockaddr *)&clientInfo, &addrlen);
        send(forClientSocketfd, message, sizeof(message), 0);
        recv(forClientSocketfd, inputBuffer, sizeof(inputBuffer), 0);
        printf("Received from client: %s\n", inputBuffer);
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM