本文整理汇总了C++中recv函数的典型用法代码示例。如果您正苦于以下问题:C++ recv函数的具体用法?C++ recv怎么用?C++ recv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了recv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: strcpy
//! Starts the socket thread
void SocketThread::run() {
std::string p_socketFile = "/tmp/isis_qview_" + Isis::Application::UserName();
struct sockaddr_un p_socketName;
p_socketName.sun_family = AF_UNIX;
strcpy(p_socketName.sun_path,p_socketFile.c_str());
int p_socket;
// Create a socket
if ((p_socket = socket(PF_UNIX,SOCK_STREAM,0)) < 0) {
std::string msg = "Unable to create socket";
std::cerr << msg << std::endl;
return;
}
//const long unsigned int timeout = 1;
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100000;
if(setsockopt(p_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)) != 0) {
std::string msg = "Unable set socket timeout";
std::cerr << msg << std::endl;
return;
}
// Bind the file to the socket
int status = bind(p_socket,(struct sockaddr *)&p_socketName, sizeof(p_socketName));
if (status < 0) {
std::string msg = "Unable to bind to socket [" + p_socketFile + "]";
std::cerr << msg << std::endl;
return;
}
// Set up to listen to the socket
if (listen(p_socket,5) < 0) {
std::string msg = "Unable to listen to socket [" + p_socketFile + "]";
std::cerr << msg << std::endl;
return;
}
p_done = false;
while(!p_done) {
// Accept Socket
socklen_t len;
int childSocket = accept(p_socket, (struct sockaddr *)&p_socketName, &len);
if (childSocket < 0) {
continue; // probably timed out, we cant do anything about this anyways
}
// Receive Data
int bytes;
char buf[1024*1024];
if ((bytes = recv(childSocket,&buf,1024*1024,0)) < 0) {
std::string msg = "Unable to read from socket [" + p_socketFile + "]";
std::cerr << msg << std::endl;
return;
}
// Push everything onto our string buffer
Isis::iString buffer;
for (int i=0; i<bytes; i++) buffer += buf[i];
while (buffer.size() > 0) {
Isis::iString token = buffer.Token(" ");
if (token == "raise") {
emit focusApp();
}
else emit newImage(token.c_str());
}
};
}
示例2: dnsReplyHandler
static int
dnsReplyHandler(int abort, FdEventHandlerPtr event)
{
int fd = event->fd;
char buf[2048];
int len, rc;
ObjectPtr object;
unsigned ttl = 0;
AtomPtr name, value, message = NULL;
int id;
int af;
DnsQueryPtr query;
AtomPtr cname = NULL;
if(abort) {
dnsSocketHandler = NULL;
rc = establishDnsSocket();
if(rc < 0) {
do_log(L_ERROR, "Couldn't reestablish DNS socket.\n");
/* At this point, we should abort all in-flight
DNS requests. Oh, well, they'll timeout anyway. */
}
return 1;
}
len = recv(fd, buf, 2048, 0);
if(len <= 0) {
if(errno == EINTR || errno == EAGAIN) return 0;
/* This is where we get ECONNREFUSED for an ICMP port unreachable */
do_log_error(L_ERROR, errno, "DNS: recv failed");
dnsGethostbynameFallback(-1, message);
return 0;
}
/* This could be a late reply to a query that timed out and was
resent, a reply to a query that timed out, or a reply to an
AAAA query when we already got a CNAME reply to the associated
A. We filter such replies straight away, without trying to
parse them. */
rc = dnsReplyId(buf, 0, len, &id);
if(rc < 0) {
do_log(L_WARN, "Short DNS reply.\n");
return 0;
}
if(!findQuery(id, NULL)) {
return 0;
}
rc = dnsDecodeReply(buf, 0, len, &id, &name, &value, &af, &ttl);
if(rc < 0) {
assert(value == NULL);
/* We only want to fallback on gethostbyname if we received a
reply that we could not understand. What about truncated
replies? */
if(rc < 0) {
do_log_error(L_WARN, -rc, "DNS");
if(dnsUseGethostbyname >= 2 ||
(dnsUseGethostbyname &&
(rc != -EDNS_HOST_NOT_FOUND && rc != -EDNS_NO_RECOVERY &&
rc != -EDNS_FORMAT))) {
dnsGethostbynameFallback(id, message);
return 0;
} else {
message = internAtom(pstrerror(-rc));
}
} else {
assert(name != NULL && id >= 0 && af >= 0);
}
}
query = findQuery(id, name);
if(query == NULL) {
/* Duplicate id ? */
releaseAtom(value);
releaseAtom(name);
return 0;
}
/* We're going to use the information in this reply. If it was an
error, construct an empty atom to distinguish it from information
we're still waiting for. */
if(value == NULL)
value = internAtom("");
again:
if(af == 4) {
if(query->inet4 == NULL) {
query->inet4 = value;
query->ttl4 = current_time.tv_sec + ttl;
} else
releaseAtom(value);
} else if(af == 6) {
if(query->inet6 == NULL) {
query->inet6 = value;
query->ttl6 = current_time.tv_sec + ttl;
} else
releaseAtom(value);
} else if(af == 0) {
/* Ignore errors in this case. */
if(query->inet4 && query->inet4->length == 0) {
//.........这里部分代码省略.........
示例3: exe_cgi
//.........这里部分代码省略.........
if(strcasecmp(method, "GET") == 0 )
{
clear_header(sock); //"GET" send val by url ,already get
}
int ret = 0;
if(strcasecmp(method, "POST") == 0 ) //different
{
do
{
memset(buf, '\0', sizeof(buf));
ret = get_line(sock, buf, sizeof(buf));
if( strncasecmp(buf, "Content-Length: ", 16) == 0)
{
content_length = atoi(&buf[16]);
}
}while( (ret > 0) && strcmp(buf, "\n") != 0 );
printf("content_length = %d\n", content_length);
if( content_length == -1 )
{
echo_errno(sock);
return;
}
}
///////////// (8.11) /////////////////////////////
sprintf(buf, "HTTP/1.0 200 OK\r\n\r\n");
send(sock, buf, strlen(buf), 0);
if( pipe(cgi_input) < 0 )
{
echo_errno(sock);
return;
}
if( pipe(cgi_output) < 0 )
{
echo_errno(sock);
return;
}
pid_t id = fork();
if(id == 0) //child
{
close(cgi_input[1]);
close(cgi_output[0]);
dup2(cgi_input[0], 0);
dup2(cgi_output[1], 1);
sprintf(method_env, "REQUEST_METHOD=%s", method);
putenv(method_env);
if( strcasecmp(method, "GET") == 0 ) //GET
{
sprintf(query_string_env, "QUERY_STRING=%s", query_string);
putenv(query_string_env);
}
else //POST
{
sprintf(content_length_env, "CONTENT_LENGTH=%d", content_length);
putenv(content_length_env);
}
execl(path, path, NULL);
//run here , execl wrong
exit(1);
}
else //father
{
close(cgi_input[0]);
close(cgi_output[1]);
// dup2(cgi_input[1], 1);
// dup2(cgi_output[0], 0);
char c = '\0';
int i =0;
if( strcasecmp(method, "POST") == 0 )
{
for(; i < content_length; ++i)
{
recv(sock, &c, 1, 0);
printf("%c", c);
write(cgi_input[1], &c, 1);
}
}
int ret = 0;
while( read(cgi_output[0], &c, 1) > 0)
{
send(sock, &c, 1, 0);
}
waitpid(id, NULL, 0);
}
}
示例4: epFUI_OnRecv
int epFUI_OnRecv(struct ep_t *pep, struct ep_con_t *pnode)
{
// static int rtimes = 0;
// printf("\r--------!!!!!! OnRecv !!!!! --------%8.8x\r",rtimes++);
int ret;
// char rbuf[100];
struct tmsxx_app *pss;
int32_t retRecv, retFramelen, recvTotal;
int32_t reserved;
char *pdata;
// printf("epFUI_OnRecv()\n");
if (pnode->ptr == NULL) {
printf("wait \n");
sleep(1);
return 1;
}
#ifdef CONFIG_TEST_NET_STRONG
struct tms_context *ptms_context = &(((struct tmsxx_app *)(pnode->ptr))->context);
ptms_context->net_pack_id++;
#endif
pss = (struct tmsxx_app *)pnode->ptr;
//pss->morebyte = 100;
if (pss->enable_lbb == 0) {
pdata = bipbuffer_Reserve(&pss->bb, pss->morebyte, &reserved);
}
else {
// printf("bipbuffer_Reserve lbb ");
pdata = bipbuffer_Reserve(&pss->lbb, pss->lbyte, &reserved);
int size;
bipbuffer_GetContiguousBlock(&pss->lbb, &size);
// printf("size %d\n",size);
}
// printf("1-1 ");
// sleep(1);
if (pdata == NULL) {
retRecv = 1;//无用,必须大于0
// printf("2-0 ");
}
// 固定环形缓存
else if (pss->enable_lbb == 0) {
// printf("want to recv %d\n",reserved);
retRecv = recv(pnode->sockfd, pdata, reserved, 0);
// printf("retRecv %d\n", retRecv);
// printf("recv count = %d\n", retRecv);
// printf("2-1 %d ", retRecv);
// printf("this times recv %d\n",retRecv);
bipbuffer_Commit(&pss->bb, retRecv);
}
// 大型环形缓存,只够存储一帧数据,填满缓存前不找合法帧,
// 填满后无论是否找到合法帧均释放
else {
retRecv = recv(pnode->sockfd, pdata, reserved, 0);
// printf("recv count = %d\n", retRecv);
// printf("2-2 %d ", retRecv);
bipbuffer_Commit(&pss->lbb, retRecv);
pss->lbyte -= retRecv;
if (pss->enable_lbb == 1 && pss->lbyte > 0) {
// printf("end 2-3\n");
return retRecv;
}
else {
// printf("e-4 ");
struct bipbuffer tbb;
tbb = pss->lbb;
pss->lbb = pss->bb;
pss->bb = tbb;
}
}
//bipbuffer_PrintMemory(&pss->bb);
_Again:
;
// printf("_Again:");
pdata = bipbuffer_GetContiguousBlock(&pss->bb, &recvTotal);
if (bipbuffer_GetUsedSize(&pss->bb) >= 40 && recvTotal < 40) {
int unuse;
// printf("a -1 ");
bipbuffer_GetUnContiguousBlock(&pss->bb, &unuse);
}
if (recvTotal >= 40) {
// printf("a -2 ");
ret = glink_FindFrame((int8_t *)pdata, &recvTotal, &retFramelen);
}
else {
// printf("a -3 ");
ret = -6;
retFramelen = 0;
}
//.........这里部分代码省略.........
示例5: internal__hydra_connect
//.........这里部分代码省略.........
{
if (verbose)
perror("error:");
if (errno == EADDRINUSE)
{
src_port--;
sin.sin_port = htons(src_port);
}
else
{
if (errno == EACCES && (getuid() > 0))
{
printf("You need to be root to test this service\n");
return -1;
}
}
}
else
bind_ok=1;
}
}
if (use_proxy > 0) {
target.sin_port = htons(proxy_string_port);
memcpy(&target.sin_addr.s_addr, &proxy_string_ip, 4);
} else {
target.sin_port = htons(port);
memcpy(&target.sin_addr.s_addr, &host, 4);
}
target.sin_family = AF_INET;
signal(SIGALRM, alarming);
do {
if (fail > 0)
sleep(WAIT_BETWEEN_CONNECT_RETRY);
alarm_went_off = 0;
alarm(waittime);
ret = connect(s, (struct sockaddr *) &target, sizeof(target));
alarm(0);
if (ret < 0 && alarm_went_off == 0) {
fail++;
if (verbose && fail <= MAX_CONNECT_RETRY)
fprintf(stderr, "Process %d: Can not connect [unreachable], retrying (%d of %d retries)\n", (int) getpid(), fail, MAX_CONNECT_RETRY);
}
} while (ret < 0 && fail <= MAX_CONNECT_RETRY);
if (ret < 0 && fail > MAX_CONNECT_RETRY) {
if (debug)
printf("DEBUG_CONNECT_UNREACHABLE\n");
/* we wont quit here, thats up to the module to decide what to do
* fprintf(stderr, "Process %d: Can not connect [unreachable], process exiting\n", (int)getpid());
* hydra_child_exit(1);
*/
extern_socket = -1;
ret = -1;
return ret;
}
ret = s;
extern_socket = s;
if (debug)
printf("DEBUG_CONNECT_OK\n");
if (use_proxy == 2) {
buf = malloc(4096);
memset(&target, 0, sizeof(target));
memcpy(&target.sin_addr.s_addr, &host, 4);
target.sin_family = AF_INET;
#ifdef CYGWIN
if (proxy_authentication == NULL)
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port);
else
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntoa((struct in_addr) target.sin_addr), port, proxy_authentication);
#else
if (proxy_authentication == NULL)
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port);
else
snprintf(buf, 4096, "CONNECT %s:%d HTTP/1.0\r\nProxy-Authorization: Basic %s\r\n\r\n", inet_ntop(AF_INET, &target.sin_addr, out, sizeof(out)), port,
proxy_authentication);
#endif
send(s, buf, strlen(buf), 0);
recv(s, buf, 4096, 0);
if (strncmp("HTTP/", buf, strlen("HTTP/")) == 0 && (tmpptr = index(buf, ' ')) != NULL && *++tmpptr == '2') {
if (debug)
printf("DEBUG_CONNECT_SSL_OK\n");
} else {
if (debug)
printf("DEBUG_CONNECT_SSL_FAILED (Code: %c%c%c)\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2));
if (verbose)
fprintf(stderr, "Error: CONNECT call to proxy failed with code %c%c%c\n", *tmpptr, *(tmpptr + 1), *(tmpptr + 2));
close(s);
extern_socket = -1;
ret = -1;
free(buf);
return ret;
}
free(buf);
}
fail = 0;
return ret;
}
return ret;
}
示例6: seq_response
static void * seq_response(void * arg)
{
prctl(PR_SET_NAME, "ccnfd_seq", 0, 0, 0);
int sock;
memcpy(&sock, (int * )arg, sizeof(int));
free(arg);
uint32_t payload_size;
uint32_t name_len;
char str[MAX_NAME_LENGTH];
struct content_name * name = NULL;
int chunks;
int file_len;
int rv = -1;
struct segment seg;
if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
if (name_len > MAX_NAME_LENGTH)
name_len = MAX_NAME_LENGTH - 1;
if (recv(sock, str, name_len, 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
str[name_len] = '\0';
if (recv(sock, &chunks, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
if (recv(sock, &file_len, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
name = content_name_create(str);
/*
if ((seg.obj = CS_getSegment(name)) != NULL) {
log_error(g_log, "seq_response: found segment %s in CS", name->full_name);
rv = 0;
goto RETURN_CONTENT;
}
*/
log_print(g_log, "seq_response: retrieving %d chunks with base: %s",
chunks, name->full_name);
/* tell the broadcaster not to query the strategy layer to lower overhead */
ccnfdnb_opt_t opts;
opts.mode = 0;
/* we add a dummy component of maximum length to make sure all the segment
* names willl be valid.
*/
snprintf(str, MAX_NAME_LENGTH - name->len - 1, "%d", chunks);
if (content_name_appendComponent(name, str) != 0) {
log_error(g_log, "could not append component to name (too long?)");
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
int chunk_size = (chunks > 1) ? ccnf_max_payload_size(name) : file_len;
content_name_removeComponent(name, name->num_components - 1);
completed_jobs_t dld_segments;
pthread_mutex_init(&dld_segments.mutex, NULL);
pthread_cond_init(&dld_segments.cond, NULL);
dld_segments.completed = linked_list_init(free);
seg.name = name;
seg.num_chunks = chunks;
seg.opts = &opts;
seg.chunk_size = chunk_size - 1;
seg.obj = malloc(sizeof(struct content_obj));
seg.obj->name = name;
seg.obj->data = malloc(file_len);
if (!seg.obj->data) {
log_error(g_log, "retrieve_segment: failed to allocated %d bytes!", file_len);
send(sock, &rv, sizeof(uint32_t), 0);
goto END_SEQ_RESP;
}
seg.obj->size = file_len;
if ((rv = retrieve_segment(&seg)) < 0) {
log_error(g_log, "retrieve_segment: failed to get %s!", name->full_name);
//.........这里部分代码省略.........
示例7: badSource
wchar_t * badSource(wchar_t * data)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
return data;
}
开发者ID:maurer,项目名称:tiamat,代码行数:71,代码来源:CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_open_61b.cpp
示例8: receive_data
int
receive_data (int fd)
{
char buf[MSG_BUF_SIZE];
int ret = 0;
while (1) {
ret = recv(fd, buf, MSG_BUF_SIZE, 0);
if ((-1 == ret) && (errno == EWOULDBLOCK || errno == EAGAIN)) {
continue;
}
else if(-1 == ret) {
syslog(LOG_ERR, "recv error is failed ! : %s\n" , strerror(errno));
goto err_exit;
}
break;
}
command_t *recv_data;
recv_data = (command_t *)buf;
printf("CMD : %c \n", recv_data->cmd );
if (recv_data->cmd == M_CMD_L) {
response_t *login_rsp;
login_rsp = constr_send_rsp(recv_data);
if (login_rsp == NULL) {
syslog(LOG_ERR, "constr_send_rsp() is failed !\n");
return -1;
}
ret = send(fd, login_rsp, LOG_RSP_LEN, 0);
if (ret == -1) {
syslog(LOG_ERR, "send() login_rsp is failed !\n");
return -1;
}
free(login_rsp);
}
else if (recv_data->cmd == M_CMD_S) {
//parser cfg data ,call funtion
sim_trader_t *sim_data;
trad_sim_cfg_t *cfg;
cfg = (trad_sim_cfg_t *)recv_data->data;
sim_data = sim_trader_init(cfg);
if (sim_data == NULL) {
syslog(LOG_ERR,"sim_trader_init() IS failed \n");
return -1;
}
int size = sim_trader_size(sim_data);
ret = sim_trader_start(sim_data, fd);
if (ret == -1) {
syslog(LOG_ERR,"sim_trader_start() IS failed \n");
return -1;
}
sim_trader_destroy(sim_data);
}
else {
syslog(LOG_ERR , "unexpected cmd %c , ID : %d , len : %d \n",
recv_data->cmd,
recv_data->id,
recv_data->len);
return -1;
}
err_exit:
if (fd > 0) {
close(fd);
syslog(LOG_ERR, " recv_data() fd is close ! \n");
}
return -1;
}
示例9: main
void main()
{
int ret;
int i, j, k, maxfd, listenfd, connfd;
// int sockfd[LISTENQ];
int reuse = 1;
fd_set rset, wset;
char buf[WAN_MSG_MAX_SIZE];
char cmd_buf[WAN_MSG_MAX_SIZE];
char tmp_buf[WAN_MSG_MAX_SIZE];
char * tmp_buf_pointer;
char * endptr;
char opt[64];
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
uint16_t csum;
uint16_t msg_size_net;
uint16_t msg_size;
signal(SIGPIPE, sig_pipe_handler);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd < 0) {
perror("socket");
exit(1);
}
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
perror("setsockopet");
exit(1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(WAN_PORT);
if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind");
exit(1);
}
listen(listenfd, LISTENQ);
maxfd = listenfd; /* initialize */
do {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
socket_alive = 1;
while(socket_alive) {
FD_ZERO(&rset);
FD_SET(connfd, &rset);
maxfd = connfd;
switch(select(maxfd+1, &rset, NULL, NULL, NULL)) {
case -1:
socket_alive = 0;
close(connfd);
break;
case 0:
break;
default:
#ifdef WANP
if(recv(connfd, buf, WAN_HEADER_SIZE, MSG_WAITALL) != WAN_HEADER_SIZE) {
perror("recv");
close(connfd);
break;
}
Wan_GetSize(buf, &msg_size);
if(recv(connfd, buf + WAN_HEADER_SIZE, msg_size - WAN_HEADER_SIZE, MSG_WAITALL) != msg_size - WAN_HEADER_SIZE) {
perror("recv");
close(connfd);
break;
}
if(Wan_CheckMsg(buf, msg_size) < 0) {
perror("wan message check error");
close(connfd);
break;
}
#else
for(i = 0; i < WAN_MSG_MAX_SIZE; i++) {
if(recv(connfd, buf+i, 1, 0) != 1) {
perror("recv");
close(connfd);
break;
}
if('\n' == buf[i]) {
msg_size = i + 1;
break;
}
}
#endif
buf[msg_size] = '\0';
GetCmd(buf, cmd_buf);
// printf("cmd: %s\n", cmd_buf);
// printf("cmd(buf): %s\n", buf);
*tmp_buf = '\0';
if(strcmp(cmd_buf, Hello.Name) == 0) {
ret = DoHello(buf);
if(0 == ret) {
RespOK(buf, cmd_buf, NULL);
} else if(HELP_HELLO == ret) {
tmp_buf_pointer = tmp_buf;
tmp_buf_pointer += sprintf(tmp_buf_pointer, "hello: \r\n");
//.........这里部分代码省略.........
示例10: capacityEstimation_pairs
double capacityEstimation_pairs(int tcpsock)
{
extern int udpsock0;
char buf[2000];
int ret1 = 0, ret2 = 0;
struct timeval t1, t2, tout;
double gap = 0;
double cap = -1, mindcap = -1;
pcapestack pcapack;
pcapack.header.ptype = P_CAP_ACK;
pcapack.header.length = 4;
int ret = 0;
int niters = 0, nfound = 0;
double mindelay1 = INT_MAX;
double mindelay2 = INT_MAX;
double mindelaysum = INT_MAX;
double owd1 = 0, owd2 = 0;
int mindflag1, mindflag2, mindsumflag;
fd_set readset;
int maxfd = (udpsock0 > tcpsock) ? udpsock0+1 : tcpsock+1;
while(1)
{
niters++;
mindflag1 = mindflag2 = mindsumflag = 0;
cap = ret1 = ret2 = -1;
FD_ZERO(&readset);
FD_SET(udpsock0, &readset);
tout.tv_sec = 1; tout.tv_usec = 0;
ret = select(maxfd, &readset, NULL, NULL, &tout);
if(ret < 0)
{
fprintf(stderr, "select error\n");
return -1;
}
else if(ret == 0)
{
goto noudp;
}
if(FD_ISSET(udpsock0, &readset))
{
ret1 = recv(udpsock0, buf, 2000, 0);
if(ret1 == -1)
{
fprintf(stderr, "recv error on UDP\n");
return -1;
}
#ifndef OSX
if (ioctl(udpsock0, SIOCGSTAMP, &t1) < 0)
{
perror("ioctl-SIOCGSTAMP");
gettimeofday(&t1,NULL);
}
#else
gettimeofday(&t1, NULL);
#endif
owd1 = fabs(-1e3*(*(double *)buf - (t1.tv_sec + t1.tv_usec/1.0e6)));
mindflag1 = (mindelay1 > owd1) ? 1 : 0;
mindelay1 = (mindelay1 > owd1) ? owd1 : mindelay1;
}
FD_ZERO(&readset);
FD_SET(udpsock0, &readset);
tout.tv_sec = 10; tout.tv_usec = 0;
ret = select(maxfd, &readset, NULL, NULL, &tout);
if(ret < 0)
{
fprintf(stderr, "select error\n");
return -1;
}
else if(ret == 0)
{
goto noudp;
}
if(FD_ISSET(udpsock0, &readset))
{
ret2 = recv(udpsock0, buf, 2000, 0);
if(ret2 == -1)
{
fprintf(stderr, "recv error on UDP\n");
return -1;
}
#ifndef OSX
if (ioctl(udpsock0, SIOCGSTAMP, &t2) < 0)
{
perror("ioctl-SIOCGSTAMP");
gettimeofday(&t2,NULL);
}
#else
gettimeofday(&t2,NULL);
#endif
owd2 = fabs(-1e3*(*(double *)buf - (t2.tv_sec + t2.tv_usec/1.0e6)));
mindflag2 = (mindelay2 > owd2) ? 1 : 0;
mindelay2 = (mindelay2 > owd2) ? owd2 : mindelay2;
}
if(ret1 != ret2 || ret1 == -1 || ret2 == -1)
//.........这里部分代码省略.........
示例11: main
//.........这里部分代码省略.........
perror("server: bind");
continue;
}
break;
}
// Debug de erro
if (p == NULL) {
fprintf(stderr, "servidor: falha ao realizar 'bind'\n");
return 2;
}
// Necessario devido à chamada 'getaddrinfo' acima
freeaddrinfo(servinfo);
// Anuncia que está apto para receber conexões
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
printf("servidor: aguardando conexoes...\n");
// Loop de aceitacao principal
while(1) {
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
// perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
printf("servidor: conexao obtida de %s\n", s);
// Processo filho
if (!fork()) {
// Processo filho nao precisa da escuta
close(sockfd);
ativo = 1;
while(ativo){
// Recebe a opcao do client
if(recv(new_fd,opt, 4, 0) == -1);
perror("recv");
switch(opt[0]){
case '1':
// Listar todos os Ids dos filmes com seus respectivos
// titulos
getAllMovieTitles(new_fd);
break;
case '2':
// Dado o Id de um filme, retornar a sinopse
getMovieSynById(new_fd, opt);
break;
case '3':
// Dado o Id de um filme, retornar todas as informações
// desse filme
getMovieById(new_fd, opt);
break;
case '4':
// Listar todas as informações de todos os filmes;
getAllMovies(new_fd);
break;
case '5':
// Finaliza conexao
ativo = 0;
break;
default:
printf("Opcao nao valida. Tente novamente\n");
break;
}
}
close(new_fd);
exit(0);
}
// processo pai nao precisa da nova conexao
close(new_fd);
}
return 0;
}
示例12: envia_pacote_modulo_03
int * envia_pacote_modulo_03(int pacote[])
{
int sockfd = 0; /* File Description do Socket */
int numbytes = 0; /* Numero de bytes recebidos */
int i = 0;
int sin_size = sizeof(struct sockaddr_in); /* Tamanho da estrutura */
struct sockaddr_in serv_addr; /* informação de endereço de informação */
#ifdef COMENTARIOS_M1
//Criando o socket
printf("Cria Socket\n");
#endif
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
//printf("Pacote sendo enviado para o modulo 03 - %d - %d\n", sizeof(pacote), (TAM_PKG * sizeof(int)));
// printf("ENVIADO: \n");
// for(i=0; i<TAM_PKG; i++)
// printf("%d ",pacote[i]);
serv_addr.sin_family = AF_INET; /* host byte order */
serv_addr.sin_port = htons(TCP_PORT_MOD3); // Porta onde o Servidor TCP estará ouvindo
serv_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(serv_addr.sin_zero), 8);/* zera o resto da estrutura */
#ifdef COMENTARIOS_M1
printf("\nConecta Socket\n");
#endif
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1)
{
perror("connect");
close(sockfd);
printf("Tentando nova conexao em alguns segundos ...\n");
sleep(5);
pacote = envia_pacote_modulo_03(pacote);
return pacote;
}
/*
* Enviando o pacote para o módulo 03
*/
#ifdef COMENTARIOS_M1_SOCKET
printf("Envia Socket\n");
for(int i = 0; i < TAM_PKG; i++)
printf("Enviando_pkg_para_M3[%d] = %d\n",i,pacote[i]);
#endif
if (send(sockfd, pacote, (TAM_PKG * sizeof(int)), 0) == -1)
{
perror("send");
exit(0);
}
/*
* Recebendo o pacote do o módulo 03
*/
#ifdef COMENTARIOS_M1_SOCKET
printf("Recebe Socket\n");
#endif
if ((numbytes=recv(sockfd, pacote, (TAM_PKG * sizeof(int)), 0)) == -1)
{
perror("recv");
exit(1);
}
#ifdef COMENTARIOS_M1_SOCKET
printf("Recebe Socket2\n");
for(int i = 0; i < TAM_PKG; i++)
printf("Recebi_pkg_no_m3[%d] = %d\n",i,pacote[i]);
#endif
/*
* Imprimindo os dados obtidos na transmissão do pacote
*/
// printf("\n\nRECEBENDO\n");
// for(int i = 0; i < TAM_PKG; i++)
// printf("%d ",pacote[i]);
close(sockfd);
return pacote;
}
示例13: ssl_connect
static int
ssl_connect(struct stream *stream)
{
struct ssl_stream *sslv = ssl_stream_cast(stream);
int retval;
switch (sslv->state) {
case STATE_TCP_CONNECTING:
retval = check_connection_completion(sslv->fd);
if (retval) {
return retval;
}
sslv->state = STATE_SSL_CONNECTING;
setsockopt_tcp_nodelay(sslv->fd);
/* Fall through. */
case STATE_SSL_CONNECTING:
/* Capture the first few bytes of received data so that we can guess
* what kind of funny data we've been sent if SSL negotiation fails. */
if (sslv->n_head <= 0) {
sslv->n_head = recv(sslv->fd, sslv->head, sizeof sslv->head,
MSG_PEEK);
}
retval = (sslv->type == CLIENT
? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
if (retval != 1) {
int error = SSL_get_error(sslv->ssl, retval);
if (retval < 0 && ssl_wants_io(error)) {
return EAGAIN;
} else {
int unused;
interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
: "SSL_accept"), retval, error, &unused);
shutdown(sslv->fd, SHUT_RDWR);
stream_report_content(sslv->head, sslv->n_head, STREAM_SSL,
THIS_MODULE, stream_get_name(stream));
return EPROTO;
}
} else if (bootstrap_ca_cert) {
return do_ca_cert_bootstrap(stream);
} else if (verify_peer_cert
&& ((SSL_get_verify_mode(sslv->ssl)
& (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
!= SSL_VERIFY_PEER)) {
/* Two or more SSL connections completed at the same time while we
* were in bootstrap mode. Only one of these can finish the
* bootstrap successfully. The other one(s) must be rejected
* because they were not verified against the bootstrapped CA
* certificate. (Alternatively we could verify them against the CA
* certificate, but that's more trouble than it's worth. These
* connections will succeed the next time they retry, assuming that
* they have a certificate against the correct CA.) */
VLOG_INFO("rejecting SSL connection during bootstrap race window");
return EPROTO;
} else {
return 0;
}
}
OVS_NOT_REACHED();
}
示例14: main
int main() {
int sock;
int client_sock;
int yes = 1;
int fifo;
// char * audio_fifo = "/tmp/audio_fifo";
int mode = 0; // 0 = Wait, 1 = Video, 2 = Audio
uint32_t remain_bytes = 0;
struct sockaddr_in addr;
struct sockaddr_in client;
addr.sin_family = AF_INET;
addr.sin_port = htons(62309);
addr.sin_addr.s_addr = INADDR_ANY;
sock = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(yes));
bind(sock, (struct sockaddr *)&addr, sizeof(addr));
if (listen(sock, 5) != 0) {
printf("Listen failed.\n");
}
uint32_t row;
char *video;
video = (char *) malloc(16588800);
if (video == NULL) {
printf("malloc failed.\n");
exit(EXIT_FAILURE);
}
char buf[65535];
// sock = socket(AF_INET, SOCK_DGRAM, 0);
//
// addr.sin_family = AF_INET;
// addr.sin_port = htons(62308);
// addr.sin_addr.s_addr = INADDR_ANY;
//
// bind(sock, (struct sockaddr *) &addr, sizeof(addr));
// fprintf(stderr, "res: %d\n", res);
// mkfifo("/tmp/audio_fifo", 0666);
// fifo = open("/tmp/audio_fifo", O_WRONLY);
// fprintf(stderr, "fifo: %d\n", fifo);
// printf("Waiting\n");
socklen_t len = sizeof(client);
client_sock = accept(sock, (struct sockaddr *)&client, &len);
// write(sock, "HELLO", 5);
while (1) {
int buf_size = remain_bytes != 0 && sizeof(buf) > remain_bytes ? remain_bytes : sizeof(buf);
int recv_bytes = recv(client_sock, buf, buf_size, 0);
// fprintf(stderr, "Receive: %i, mode: %i\n", recv_bytes, mode);
if (mode == 0) {
struct stream_info info;
memcpy(&info, buf, sizeof(stream_info));
if (info.type == T_STREAM_VIDEO) {
mode = 1;
}
if (info.type == T_STREAM_AUDIO) {
mode = 2;
}
remain_bytes = info.bytes;
} else {
if (recv_bytes != -1) {
remain_bytes -= recv_bytes;
// fprintf(stderr, "remain_bytes: %u\n", remain_bytes);
write(mode, buf, recv_bytes);
// if (mode == 1) {
// write(1, buf, recv_bytes);
// } else {
// write(fifo, buf, recv_bytes);
// }
if (remain_bytes == 0) {
remain_bytes = sizeof(stream_info);
// fprintf(stderr, "remain_bytes zero: %u\n", remain_bytes);
mode = 0;
}
}
}
// fprintf(stderr, "remain_bytes: %i\n", remain_bytes);
// recv(sock, video, sizeof(video), 0);
// struct stream_header header;
// memcpy(&header, buf, sizeof(stream_header));
// // memcpy(&row, buf, sizeof(uint32_t));
// memcpy(video + rowbytes * header.row + chunk_size * header.chunk, buf + sizeof(stream_header), chunk_size);
// memcpy(video, )
// if (header.row == height - 1) {
// write(1, video, rowbytes * height);
// }
// printf("Frame received (#%4u)\n", row);
}
// printf("%s\n", buf);
//.........这里部分代码省略.........
示例15: seq_publish
static void * seq_publish(void * arg)
{
prctl(PR_SET_NAME, "ccnfd_pubseq", 0, 0, 0);
log_print(g_log, "seq_publish: handling publish request");
int sock;
memcpy(&sock, (int * )arg, sizeof(int));
free(arg);
struct content_obj * index_chunk;
index_chunk = (struct content_obj *) malloc(sizeof(struct content_obj));
/* finish rcving the summary request packet */
/* structure of publish msg:
* publisher : int
* name_len : int
* name : char[name_len]
* timestamp : int
* size : int
* data : byte[size]
*/
uint32_t publisher;
uint32_t payload_size;
uint32_t name_len;
uint8_t name[MAX_NAME_LENGTH];
uint32_t timestamp;
uint32_t size;
uint8_t * data = NULL;
int rv = 0;
if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
if (recv(sock, &publisher, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
if (recv(sock, &name_len, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
if (name_len > MAX_NAME_LENGTH)
name_len = MAX_NAME_LENGTH - 1;
if (recv(sock, name, name_len, 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
name[name_len] = '\0';
if (recv(sock, ×tamp, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
if (recv(sock, &size, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
data = (uint8_t *) malloc(size);
if (recv(sock, data, size, 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
free(data);
rv = -1;
goto END_PUBLISH_RESP;
}
index_chunk->name = content_name_create((char * )name);
index_chunk->publisher = publisher;
index_chunk->size = size;
index_chunk->timestamp = timestamp;
index_chunk->data = data;
int num_chunks = 0;
if (recv(sock, &num_chunks, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
free(data);
rv = -1;
goto END_PUBLISH_RESP;
}
struct linked_list * chunks = linked_list_init(NULL);
int i;
for (i = 0; i < num_chunks; i++) {
if (recv(sock, &payload_size, sizeof(uint32_t), 0) == -1) {
log_error(g_log, "recv: %s.", strerror(errno));
rv = -1;
goto END_PUBLISH_RESP;
}
if (recv(sock, &publisher, sizeof(uint32_t), 0) == -1) {
//.........这里部分代码省略.........