虽然没有任何相关内容,但我正在寻找我的问题的答案。 我正在编写一个非常简单的代码,用于在运行ubuntu 14.04的虚拟机(VBOX)上运行服务器。
我关闭了我的防火墙和防病毒程序(读取它可能是相关的)
我重新检查(并查找了不同的端口)端口未使用但继续接收带有errno 88的bind()函数的返回值-1(非套接字上的套接字操作)。
我在端口7777上运行服务器。 还尝试在我的主机上运行此代码
有人可以建议我做错了吗?
p.s还检查了valgrind的代码是否有内存泄漏,但它看起来很好。
代码如下:
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <strings.h>
#include <stdlib.h>
#include <string>
#include <pthread.h>
#include <errno.h>
using namespace std;
#define NUM_OF_THREADS 3
static int connFd;
void *task1(void *);
/*
*
*/
int main(int argc, char** argv) {
int pid, portNo, listenFd;
socklen_t len; // store the size of the address
bool loop = false;
struct sockaddr_in svrAdd, clntAdd;
pthread_t threadArr[NUM_OF_THREADS];
if (argc < 2){
cerr << "ERROR: ./server <port>" << endl;
return 0;
}
portNo = atoi(argv[1]); // TODO verify the port is between 1024 and 65535
//Create the socket
if (listenFd = socket(AF_INET, SOCK_STREAM, 0) < 0){
cerr << "ERROR: cannot open socket." << endl;
return 0;
}
bzero((char*)&svrAdd, sizeof(svrAdd));
svrAdd.sin_family = AF_INET;
svrAdd.sin_addr.s_addr = INADDR_ANY;
svrAdd.sin_port = htons(portNo);
cout << "port number is : " << portNo << endl;
//bind socket
int bound = bind(listenFd, (struct sockaddr *)&svrAdd, sizeof(svrAdd));
if ( bound < 0 ){
cerr << "ERROR: cannot bind, error number: " << errno << endl;
return 0;
}
listen(listenFd, 5);
len = sizeof(clntAdd);
int noTread = 0;
while(noTread < 3){
cout << "Listening..." << endl;
if (connFd = accept(listenFd, (struct sockaddr*)&clntAdd, &len)<0){
cerr << "ERROR: cannot accept connection" << endl;
return 0;
}
else{
cout << "Connection successful" << endl;
}
pthread_create(&threadArr[noTread], NULL, task1, NULL);
noTread++;
}
for (int i=0; i < 3; i++){
pthread_join(threadArr[i], NULL);
}
/*int sockfd, newsockfd, portno, clilen, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2){
fprintf(stderr, "ERROR, no port provided");
exit(1);
}
if(sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0){
error("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr - INADDR_ANY;
if(bind(sockfd, (struct sockaddr*)&))*/
return 0;
}
void *task1(void *dummyPt){
cout << "Thread number: " << pthread_self() << endl;
char test[300];
bzero(test, 301);
bool loop = false;
while (!false){
bzero(test, 301);
read(connFd, test, 300);
string tester(test);
cout << "\n\t\t TESTER = " << tester << endl;
if(tester == "exit"){
break;
}
}
cout << "\n Closing thread and conn" << endl;
close(connFd);
}
执行的输出:
错误:无法绑定,错误号:88 端口号是:7777
RUN SUCCESSFUL(总时间:162ms)
请帮忙, 感谢。
答案 0 :(得分:1)
if (listenFd = socket(AF_INET, SOCK_STREAM, 0) < 0){
优先问题。这种情况的结果是为listenFd.
分配零或1试试这个:
if ((listenFd = socket(AF_INET, SOCK_STREAM, 0)) < 0){