我是unix socket编程的新手.我没有找到一本舒适的书或教程,所以我真的很挣扎.
这是程序代码:
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include <netinet/in.h>
int main(){
printf("one");
int socketHandle, newSocketHandle, portno;
struct sockaddr_in serverAddress, clientAddress;
printf("two");
portno = 5001;
bzero((char *) &serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(portno);
printf("three");
//creating the socket
socketHandle = socket(AF_INET, SOCK_STREAM, 0);
if(socketHandle < 0){
perror("ERROR : Socket not created.");
return -1;
}
printf("Socket created.");
//binding the socket
if(bind(socketHandle, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0){
perror("ERROR : Socket not binded.");
return -1;
}
printf("Socket binded.");
//make the socket listen
listen(socketHandle, 5);
int len = sizeof(clientAddress);
//accept the connection requests
newSocketHandle = accept(socketHandle, (struct sockaddr *) &clientAddress, &len);
if(newSocketHandle < 0){
perror("ERROR : Connection not accepted.");
}
printf("Connection accepted.");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(我试图打印one,two以及three用于调试)
但是,即使printf("one")在第一行中也行不通.光标只是一直闪烁(表示程序仍在执行中).我甚至无法弄清楚上述程序出了什么问题.使用该bzero()功能也会发出警告说
warning: incompatible implicit declaration of built-in function ‘bzero’ [enabled by default]
Run Code Online (Sandbox Code Playgroud)
我发现socket编程很难,因为不同的网站显示不同的代码.另外,请建议任何关于C/C++套接字编程的好教程.