我是网络初学者。我计划制作客户端服务器 udp,使用 pc(window xp)作为客户端,使用 mac 作为服务器。我已经做了 server.cc、client.cc、net.h 和 makefile 配置。
我使用 cygwin 在窗口中制作文件,使用 g++ 在 mac 中制作。
但是当我在cygwin中制作文件时出现错误:
g++ -c -o server.o server.cc
CC -o udp_server server.o -lsocket -lnsl
/usr/lib/gcc/i686-pc-cygwin/4.5.3/../../../../i686-pc-cygwin/bin/ld:找不到-lsocket
/usr/lib/gcc/i686-pc-cygwin/4.5.3/../../../../i686-pc-cygwin/bin/ld:找不到-lnsl collect2:ld返回1退出状态
在mac中,错误是:
c++ -c -o server.o server.cc
CC -o udp_server server.o -lsocket -lnsl
ld:找不到-lsocket clang的库:错误:链接器命令失败,退出代码为1(使用-v查看调用)
这是我的服务器代码程序:
#include "net.h"
#include <iostream> //diilangin .h
using namespace std; //ditambah
const int kWELL_KNOWN_PORT = 49998;
const char kMESSAGE[] = "UDP Bye";
int main(){
// our to be server end-point, and client endpoint
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
int cli_sock = 0, retval = 0;
// need to first ask OS for free socket descriptor
// this will be the listening socket - notr SOCK_DGRAM option now
cli_sock = socket(AF_INET, SOCK_DGRAM, 0);
if(cli_sock<0)
cerr<<"Error when trying to create socket"<<strerror(errno)<<endl;
else {
// build an internet socket address structure, defining port.
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); // any of this machines IPs will do
serv_addr.sin_port = htons(kWELL_KNOWN_PORT);
// attempt to bind socket - still need to in UDP
retval = bind(cli_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if(retval < 0)
cerr<<"Could not bind to port"<<endl<<strerror(errno)<<endl;
else {
// forever loop no more accept or listen!!!
for(;;) {
char buff[256];
// get the message and display it
//int clilen = sizeof(cli_addr); di comment
socklen_t clilen = (socklen_t)sizeof(cli_addr);
int len = recvfrom(cli_sock, buff, 256, 0, (struct sockaddr*)&cli_addr, &clilen);
buff[len] = 0;
cout<<"GOT "<<buff<<endl;
// send a reply
strcpy(buff,kMESSAGE);
if(sendto(cli_sock, buff, strlen(buff), 0, (struct sockaddr*)&cli_addr, clilen) == -1)
cerr<<"Error when sending"<<endl<<strerror(errno)<<endl;
}
}
}
return 0;
}
有人有改进我的程序的建议吗?
丹尼尔