当前位置: 技术问答>linux和unix
谁有Linux下的TCP/IP编程的例子,侦听,接收,发送,继续循环侦听
来源: 互联网 发布时间:2015-10-15
本文导语: ? | #include #include #include #include #include #include #include #include #include #include #include #define SOCKET_ERROR -1 #define INVALID_SOCKET -1 int CreateListeningSocket(const char* ip, unsigned short port, int* err_co...
?
|
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
int CreateListeningSocket(const char* ip, unsigned short port, int* err_code)
{
int on = 1;
int ret = 0;
int sockfd;
struct sockaddr_in sin;
if(lpszAddr != NULL){
sin.sin_addr.s_addr = inet_addr(lpszAddr);
assert(sin.sin_addr.s_addr != INADDR_NONE);
}else{
sin.sin_addr.s_addr = htonl(INADDR_ANY);
}
sin.sin_family=AF_INET;
sin.sin_port=htons(port);
if( (sockfd=socket(AF_INET,SOCK_STREAM,0)) != SOCKET_ERROR &&
(ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on))) != SOCKET_ERROR &&
(ret = bind(sockfd,(struct sockaddr *)&sin,sizeof(sin))) != SOCKET_ERROR &&
(ret = listen(sockfd,5)) != SOCKET_ERROR){
return sockfd;
}
if(ret == SOCKET_ERROR){
*err_code = errno;
if(sockfd != SOCKET_ERROR){
close(sockfd);
sockfd = SOCKET_ERROR;
}
}
return sockfd;
}
static void handle_client(int cs, const socdaddr_in* sinSrc)
{
char str[200];
int n;
n = ::recv(cs, str, sizeof(str), 0);
if (n == 0){
printf("socket closedn");
}else if (n