The port number in the socket address must be in big-endian byte order:
server_addr.sin_port = UInt16(4000).bigEndian
So your program actually listens on port 40975 (hex 0xA00F) and not
on port 4000 (hex 0x0FA0).
Another problem is here:
var buff_rcv: Array<CChar> = []
// ...
read(client_socket, &buff_rcv, UInt(BUFF_SIZE))
Your buffer is an empty array, but recv()
expects a buffer of size BUFF_SIZE
.
The behaviour is undefined. To get a buffer of the required size, use
var buff_rcv = [CChar](count:BUFF_SIZE, repeatedValue:0)
// ...
read(client_socket, &buff_rcv, UInt(buff_rcv.count))
Remark: Here you cast the address of an Int
to the address of an socklen_t
and pass that to the accept()
function:
client_socket = accept(server_socket, sockaddr_cast(&client_addr), socklen_t_cast(&client_addr_size))
That is not safe. If Int
and socklen_t
have different sizes then the behaviour
will be undefined. You should declare server_addr_size
and client_addr_size
as socklen_t
and remove the socklen_t_cast()
function:
client_socket = accept(server_socket, sockaddr_cast(&client_addr), &client_addr_size)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…