简体   繁体   English

Accept()函数; C语言中的简单TCP服务器

[英]Accept() function; Simple tcp server in C

I'm learning socket programming in C & downloaded a simple tcp server source file. 我正在用C学习套接字编程,并下载了一个简单的tcp服务器源文件。 I understand every line except the 2nd parameters in these functions: 我了解这些功能中除第二个参数以外的每一行:

accept(socket_fd, (struct sockaddr *)&client, &length);

bind(socket_fd, (struct sockaddr *)&server, length);

The accept + bind functions are the typical functions in "sys/types.h" & "sys/socket.h", and the man page describes it as a pointer to a struct, but I still can't understand what's really going on here. accept + bind函数是“ sys / types.h”和“ sys / socket.h”中的典型函数,手册页将其描述为指向结构的指针,但我仍然无法理解到底发生了什么这里。

Can someone please explain what is going on in the second parameter? 有人可以解释第二个参数是什么吗? The brackets, pointer and address symbols are confusing me in the same expression. 方括号,指针和地址符号在同一表达式中使我感到困惑。

Thanks in advance! 提前致谢!

The & symbol essentially means "get the address of the value/object". &符号本质上意味着“获取值/对象的地址”。 The (struct sockaddr *) is a cast. (struct sockaddr *)(struct sockaddr *) It tells the compiler that you want to treat the address as a pointer to a sockaddr structure. 它告诉编译器您要将地址视为指向sockaddr结构的指针。 So together, it is telling the compiler that client can be treated as a sockaddr structure and to pass the address of it to the function. 因此,这一起告诉编译器可以将client视为sockaddr结构并将其地址传递给函数。 In the case of the accept function, the address of the connecting socket will be stored in the given structure. 对于accept函数,连接套接字的地址将存储在给定的结构中。

What's happening is that accept and bind function are expecting struct sockaddr pointers, and your client and server variables are probably declared as (struct sockaddr *) . 发生的情况是acceptbind函数期望使用struct sockaddr指针,并且您的clientserver变量可能声明为(struct sockaddr *) So, in order to avoid a warning in C or a compiler error in C++ , you need an explicit cast which you do by putting the expression: 因此,为了避免C警告C ++编译器错误,你需要你通过把表达做一个明确的转换:

(struct sockaddr *)

Before your parameter. 在输入参数之前。

And you need the ampersand, because client and server are not pointers. 而且您需要使用&号,因为clientserver不是指针。 They were probably declared like: 它们可能被声明为:

struct sockaddr_in client, server;

It's also worth mentioning that the structures are closely related. 还值得一提的是,这些结构是紧密相关的。 Take a look at the picture from Stevens UnP . 看看Stevens UnP的图片。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM