我缺少什么来创建套接字

What am i missing to create socket?

本文关键字:创建 套接字 什么      更新时间:2023-10-16

我正试图用C创建一个客户端/服务器,这是我第一次学习C编程,我只想通过本地主机连接,而不是通过互联网连接,我缺少什么。我该如何修复它,让我的服务器启动并运行,以及我应该键入什么来让我的客户端连接到我的服务器。

我需要创建一个可以与客户端进行发送和接收的服务器。对不起,我是C编程的新手,只是在学习阶段,请原谅我缺乏经验,我很想向这里的专家学习。

下面是我在主中的代码

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>

using namespace std;
int main()
{
int serverFd;
int clientFd;
struct sockaddr_un serverAddress;
cout << "" << endl;
cout << "Running server program 'css' ...... " << endl;
cout << "" << endl;

// SOCKET CREATION PART - SERVER
serverFd = socket (AF_LOCAL, SOCK_STREAM, 0);
/* Set domain type */
serverAddress.sun_family = AF_LOCAL; 
/* Set name */ 
strcpy (serverAddress.sun_path, "Server"); 
/* Remove file if it already exists */ 
unlink ("Server"); 
/* Create file */
bind (serverFd, serverSockAddrPtr, serverLen);
// SOCKET CREATION END - SERVER
return 0;
}

我得到的错误:

CountryServer.c:39:17: error: ‘serverSockAddrPtr’ was not declared in this scope
CountryServer.c:39:36: error: ‘serverLen’ was not declared in this scope

正如错误所说,您使用的名称(serverSockAddrPtrserverLen)尚未声明。您想要的是serverAddress结构的地址大小

bind (serverFd, 
      reinterpret_cast<sockaddr const *>(&serverAddress), 
      sizeof serverAddress);

您缺少一些标头。

根据本手册页,struct sockaddr_unsys/un.h中。