int main(int argc, char *argv[]) { struct addrinfo *ailist, *aip; struct addrinfo hint; int sockfd, err; if (argc != 2) err_quit("usage: ruptime hostname"); hint.ai_flags = 0; hint.ai_family = 0; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = 0; hint.ai_addrlen = 0; hint.ai_canonname = NULL; hint.ai_addr = NULL; hint.ai_next = NULL; if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0) err_quit("getaddrinfo error: %s", gai_strerror(err)); for (aip = ailist; aip != NULL; aip = aip->ai_next) { if ((sockfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0) err = errno; if (connect_retry(sockfd, aip->ai_addr, aip->ai_addrlen) < 0) { err = errno; } else { print_uptime(sockfd); exit(0); } } fprintf(stderr, "can't connect to %s: %s\n", argv[1], strerror(err)); exit(1); }
int main(int argc, char *argv[]) { struct addrinfo *ailist, *aip; struct addrinfo hint; int sockfd, err; if (argc != 2) err_quit("usage: ruptime hostname"); memset(&hint, 0, sizeof(hint)); hint.ai_socktype = SOCK_STREAM; hint.ai_canonname = NULL; hint.ai_addr = NULL; hint.ai_next = NULL; if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0) err_quit("getaddrinfo error: %s", gai_strerror(err)); // 如果服务器支持多重网络接口或多重网络协议,getaddrinfo可能会返回多个后续地址 // 轮流尝试对每个地址进行连接,找到一个便可停止 for (aip = ailist; aip != NULL; aip = aip->ai_next) { if ((sockfd = connect_retry(aip->ai_family, SOCK_STREAM, 0, aip->ai_addr, aip->ai_addrlen)) < 0) { err = errno; } else { print_uptime(sockfd); exit(0); } } err_exit(err, "can't connect to %s", argv[1]); }
int main(int argc, char *argv[]) { int sockfd, ret; char *host; uint16_t port = DEFAULT_PORT; struct addrinfo *p_addrlist = NULL; struct addrinfo hint; struct sockaddr_in sa_in; if(argc == 1) { host = get_defaulthost(); } if(argc >= 2) { host = argv[1]; } if(argc >= 3) { port = (uint16_t)atoi(argv[2]); } /* * get remote addr from input host or default host */ init_addrinfo(&hint, SOCK_STREAM); if((ret = getaddrinfo(host, NULL, &hint, &p_addrlist)) != 0) err_quit("getaddrinfo error: %s", gai_strerror(ret)); if(p_addrlist != NULL) memcpy((void *)&sa_in, (void *)p_addrlist->ai_addr, sizeof(sa_in)); else { sa_in.sin_family = AF_INET; sa_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK); } sa_in.sin_port = htons(port); if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) err_sys("socket error: %s", strerror(errno)); /* * !!! * pay attention to the alen, it is not correct by input sizeof(struct sockaddr) * because the struct size depends on the machine archtect */ if(connect_retry(sockfd, (struct sockaddr *)&sa_in, INET_ADDRSTRLEN) < 0) err_quit("connect fail: %s", strerror(errno)); print_response(sockfd); return 0; }
int sock_conn_server(struct sockaddr_in *cliaddr, struct connect_serv *conn) { int serv_fd; serv_fd = sock_server_init(cliaddr, conn->IP, conn->Port); if( !connect_retry(serv_fd, (const struct sockaddr *)cliaddr, sizeof(struct sockaddr_in)) ){ close(serv_fd); printf("connect server connect fail...\n"); return -1; } printf("连接connect server 成功...%d\n", serv_fd); return serv_fd; }
int main(int argc, char *argv[]) { int fd, sockfd, err, text, c; struct stat sbuf; char *host; struct addrinfo *ailist, *aip; err = 0; text = 0; while ((c = getopt(argc, argv, "t")) != -1) { switch (c) { case 't': text = 1; break; case '?': err = 1; break; } } if (err || (optind != argc - 1)) err_quit("usage: print [-t] filename"); if ((fd = open(argv[optind], O_RDONLY)) < 0) err_sys("print: can't open %s", argv[1]); if (fstat(fd, &sbuf) < 0) err_sys("print: can't stat %s", argv[1]); if (!S_ISREG(sbuf.st_mode)) err_quit("print: %s must be a regular file\n", argv[1]); /* * Get the hostname of the host acting as the print server. */ if ((host = get_printserver()) == NULL) err_quit("print: no print server defined"); if ((err = getaddrlist(host, "print", &ailist)) != 0) err_quit("print: getaddrinfo error: %s", gai_strerror(err)); for (aip = ailist; aip != NULL; aip = aip->ai_next) { if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { err = errno; } else if (connect_retry(sockfd, aip->ai_addr, aip->ai_addrlen) < 0) { err = errno; } else { submit_file(fd, sockfd, argv[1], sbuf.st_size, text); exit(0); } } errno = err; err_ret("print: can't contact %s", host); exit(1); }
void client(int argc,char *argv[]) { struct addrinfo *alist,*aip ; struct addrinfo hint ; int sockfd ,err; if(argc != 2) { perror("usage:uptime hostname") ; } hint.ai_flags = 0 ; hint.ai_family = AF_INET ; hint.ai_socktype = SOCK_STREAM ; hint.ai_addrlen = 0 ; hint.ai_addr = NULL ; hint.ai_canonname = NULL ; hint.ai_protocol = 0 ; hint.ai_next = NULL ; if(getaddrinfo(argv[1],"uptime",&hint,&alist) != 0) { gai_strerror(errno) ; } for(aip = alist; aip != NULL ; aip = aip->ai_next) { if( (sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0) { //perror("socket failed ") ; err = errno ; } if( connect_retry(sockfd,aip->ai_addr,aip->ai_addrlen) < 0) { perror("connect_retry failed") ; err = errno ; } else { print_uptime(sockfd) ; exit(0) ; } } fprintf(stderr,"cannot connect to %s: %s\n",argv[1],strerror(err)) ; exit(1) ; }
int main(int argc, char *argv[]) { struct addrinfo *ailist, *aip; struct addrinfo hint; int socketfd, err; if (argc != 2) { printf("intput 2 arg\n"); return 0; } hint.ai_flags = 0; hint.ai_family = 0; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = 0; hint.ai_addrlen = 0; hint.ai_canonname = NULL; hint.ai_addr = NULL; hint.ai_next = NULL; if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0) { printf("getaddrinfo error\n"); return -1; } for (aip = ailist; aip != NULL; aip = aip->ai_next) { if ((socketfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0) err = errno; if (connect_retry(socketfd, aip->ai_addr, aip->ai_addrlen) < 0) { err = errno ; } else { print_uptime(socketfd); exit(0); } } fprintf(stderr, "can't, connetc, to %s\n", argv[1]); exit(1); }
int main(int argc, const char *argv[]) { #define OPEN 1 #define CLOSE 0 pthread_t show_data,wait_controller; int err,ret,alive; FD_ZERO(&wset); FD_ZERO(&rset); FD_SET(fd,&wset); FD_SET(fd,&rset); ss = fx_serial_start(); fd = client_init(7000,argv[1]); select(fd+1,&rset,&wset,NULL,NULL); restart: /*set keepalive on fd*/ alive = 1; if(setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE,&alive,sizeof(alive)) != 0) { fprintf(stderr,"set socket option error\n"); goto restart; } socket_set_keepalive(fd); ret = connect_retry(fd,(struct sockaddr *)&clientaddr,sizeof(clientaddr)); if(ret == -1) { printf("cannot connect to server\n"); exit(1); } signal(SIGINT,free_space); err = pthread_create(&wait_controller,NULL,Control_controller,NULL); if(err != 0) { fprintf(stderr,"cannot create the thread\n"); exit(1); } while(1) { header__init(&MS.mh); sensor_info__init(&MS.si); sensor_t__init(&MS.st); Get_data(); //test(); sleep(293); //sleep 5 mins } //err = pthread_create(&show_data,NULL,Sensor_data,NULL); //if(err != 0) // { // fprintf(stderr,"cannot create the thread\n"); // exit(1); //} //pthread_join(show_data, NULL); pthread_join(wait_controller, NULL); //while(1) getchar(); return 0; }
/* * Single thread to communicate with the printer. * * LOCKING: acquires and releases joblock and configlock. */ void * printer_thread(void *arg) { struct job *jp; int hlen, ilen, sockfd, fd, nr, nw, extra; char *icp, *hcp, *p; struct ipp_hdr *hp; struct stat sbuf; struct iovec iov[2]; char name[FILENMSZ]; char hbuf[HBUFSZ]; char ibuf[IBUFSZ]; char buf[IOBUFSZ]; char str[64]; struct timespec ts = { 60, 0 }; /* 1 minute */ for (;;) { /* * Get a job to print. */ pthread_mutex_lock(&joblock); while (jobhead == NULL) { log_msg("printer_thread: waiting..."); pthread_cond_wait(&jobwait, &joblock); } remove_job(jp = jobhead); log_msg("printer_thread: picked up job %d", jp->jobid); pthread_mutex_unlock(&joblock); update_jobno(); /* * Check for a change in the config file. */ pthread_mutex_lock(&configlock); if (reread) { freeaddrinfo(printer); printer = NULL; printer_name = NULL; reread = 0; pthread_mutex_unlock(&configlock); init_printer(); } else { pthread_mutex_unlock(&configlock); } /* * Send job to printer. */ sprintf(name, "%s/%s/%d", SPOOLDIR, DATADIR, jp->jobid); if ((fd = open(name, O_RDONLY)) < 0) { log_msg("job %d canceled - can't open %s: %s", jp->jobid, name, strerror(errno)); free(jp); continue; } if (fstat(fd, &sbuf) < 0) { log_msg("job %d canceled - can't fstat %s: %s", jp->jobid, name, strerror(errno)); free(jp); close(fd); continue; } if ((sockfd = connect_retry(AF_INET, SOCK_STREAM, 0, printer->ai_addr, printer->ai_addrlen)) < 0) { log_msg("job %d deferred - can't contact printer: %s", jp->jobid, strerror(errno)); goto defer; } /* * Set up the IPP header. */ icp = ibuf; hp = (struct ipp_hdr *)icp; hp->major_version = 1; hp->minor_version = 1; hp->operation = htons(OP_PRINT_JOB); hp->request_id = htonl(jp->jobid); icp += offsetof(struct ipp_hdr, attr_group); *icp++ = TAG_OPERATION_ATTR; icp = add_option(icp, TAG_CHARSET, "attributes-charset", "utf-8"); icp = add_option(icp, TAG_NATULANG, "attributes-natural-language", "en-us"); sprintf(str, "http://%s/ipp", printer_name); icp = add_option(icp, TAG_URI, "printer-uri", str); icp = add_option(icp, TAG_NAMEWOLANG, "requesting-user-name", jp->req.usernm); icp = add_option(icp, TAG_NAMEWOLANG, "job-name", jp->req.jobnm); if (jp->req.flags & PR_TEXT) { p = "text/plain"; extra = 1; } else { p = "application/postscript"; extra = 0; } icp = add_option(icp, TAG_MIMETYPE, "document-format", p); *icp++ = TAG_END_OF_ATTR; ilen = icp - ibuf; /* * Set up the HTTP header. */ hcp = hbuf; sprintf(hcp, "POST /ipp HTTP/1.1\r\n"); hcp += strlen(hcp); sprintf(hcp, "Content-Length: %ld\r\n", (long)sbuf.st_size + ilen + extra); hcp += strlen(hcp); strcpy(hcp, "Content-Type: application/ipp\r\n"); hcp += strlen(hcp); sprintf(hcp, "Host: %s:%d\r\n", printer_name, IPP_PORT); hcp += strlen(hcp); *hcp++ = '\r'; *hcp++ = '\n'; hlen = hcp - hbuf; /* * Write the headers first. Then send the file. */ iov[0].iov_base = hbuf; iov[0].iov_len = hlen; iov[1].iov_base = ibuf; iov[1].iov_len = ilen; if (writev(sockfd, iov, 2) != hlen + ilen) { log_ret("can't write to printer"); goto defer; } if (jp->req.flags & PR_TEXT) { /* * Hack: allow PostScript to be printed as plain text. */ if (write(sockfd, "\b", 1) != 1) { log_ret("can't write to printer"); goto defer; } } while ((nr = read(fd, buf, IOBUFSZ)) > 0) { if ((nw = writen(sockfd, buf, nr)) != nr) { if (nw < 0) log_ret("can't write to printer"); else log_msg("short write (%d/%d) to printer", nw, nr); goto defer; } } if (nr < 0) { log_ret("can't read %s", name); goto defer; } /* * Read the response from the printer. */ if (printer_status(sockfd, jp)) { unlink(name); sprintf(name, "%s/%s/%d", SPOOLDIR, REQDIR, jp->jobid); unlink(name); free(jp); jp = NULL; } defer: close(fd); if (sockfd >= 0) close(sockfd); if (jp != NULL) { replace_job(jp); nanosleep(&ts, NULL); } } }
int main(int argc, char *argv[]) { int sock_serv_fd; struct sockaddr_in cliaddr; struct connect_serv conn_serv; unsigned int cid = 1011; signal(SIGPIPE, sig_handler); while(1) { if(!protocol_init(cid)){ printf("协议初始化失败...\n"); continue; } /* protocol_req_ready(&ConnectREQ, &present_info); { char buff[20] = {0}; strncpy(buff, ConnectREQ.KEY, 6); printf("开始打印协议:\n"); printf("key:%s\n", buff); printf("Length:%d\n", ConnectREQ.Length); printf("command:%#x\n", ConnectREQ.Command); printf("CID:%d%d%d%d\n", ConnectREQ.CID[3], ConnectREQ.CID[2], ConnectREQ.CID[1], ConnectREQ.CID[0]); printf("IP:%d.%d.%d.%d\n", ConnectREQ.IP[0],ConnectREQ.IP[1],ConnectREQ.IP[2], ConnectREQ.IP[3]); printf("MAC:%02x-%02x-%02x-%02x-%02x-%02x\n", ConnectREQ.MAC[0], ConnectREQ.MAC[1], ConnectREQ.MAC[2], ConnectREQ.MAC[3], ConnectREQ.MAC[4],ConnectREQ.MAC[5]); printf("presentDate:20%d-days:%d\n",*(unsigned short *)ConnectREQ.PresentDate & 0x7f, *(unsigned short *)ConnectREQ.PresentDate >> 7); printf("presentTime:%d-%d\n", ConnectREQ.PresentTime[0], ConnectREQ.PresentTime[1]); printf("model:%s\n", ConnectREQ.Model); strncpy(buff, ConnectREQ.Series, 10); printf("series:%s\n", buff); printf("joinVersion:%d.%d\n", ConnectREQ.JoinConnectVersion[0], ConnectREQ.JoinConnectVersion[1]); printf("chargerVersion:%d.%d\n", ConnectREQ.ChargerFWVersion[0], ConnectREQ.ChargerFWVersion[1]); printf("CRC:%d\n", *(u16 *)ConnectREQ.CRC16); } */ sock_serv_fd = sock_server_init(&cliaddr, JOIN_SERVER1_IP, JOIN_SERVER_PORT); if( !connect_retry(sock_serv_fd, (const struct sockaddr *)&cliaddr, sizeof(cliaddr)) ){ // 连接失败,然后连接join_server2_ip printf("jion server1 connect fail...\n"); close(sock_serv_fd); if(!(sock_serv_fd = sock_server_init(&cliaddr, JOIN_SERVER2_IP, JOIN_SERVER_PORT))){ close(sock_serv_fd); printf("join server2 connect fail...\n"); continue; } } printf("客户端连接成功...\n"); char sock_buff[1024] = {0}; // 连接join server if( !join_conn_serv(sock_serv_fd, &conn_serv)){ printf("与通信JOIN server 失败, 重新初始化...\n"); sleep(5); continue; } // if(!join_comfirm_serv(sock_serv_fd, &conn_serv, CHARGER_READY, ONLINE)){ // printf("发送JOIN SERVER确认连接失败...\n"); // exit(1); // } // sleep(2); // break; printf("\n #############################################################\n"); printf(" #############################################################\n"); printf("关闭JOIN SERVER连接,开始连接CONNECT SERVER...\n"); // JOIN SERVER 连接 shutdown(sock_serv_fd, SHUT_RDWR); close(sock_serv_fd); sock_serv_fd = -1; memset(&cliaddr, 0, sizeof(cliaddr)); printf("conn IP:%s port:%d\n", conn_serv.IP, conn_serv.Port); int g_CMD = SOCK_CMD_REQ; while(1){ // printf("sock_conn_fd=%d\n", sock_serv_fd); switch(g_CMD) { // 发送新连接 case SOCK_CMD_REQ: if((sock_serv_fd = sock_conn_server(&cliaddr, &conn_serv))<0) continue; protocol_CSREQ_ready(); if( !CServer_send(sock_serv_fd, (u8 *)CServer_req, sizeof(CServer_REQ))){ sock_close(sock_serv_fd); memset(&cliaddr, 0, sizeof(cliaddr)); printf("发送新连接失败...\n"); sleep(10); continue; } sleep(1); g_CMD = SOCK_CMD_FUP; continue; case SOCK_CMD_FUP: // 发送全更新 if((sock_serv_fd = sock_conn_server(&cliaddr, &conn_serv))<0) continue; protocol_CSFUP_ready(); if( !CServer_send(sock_serv_fd, (u8 *)CS_FUP, sizeof(CServer_FULL_UPDATE))){ sock_close(sock_serv_fd); memset(&cliaddr, 0, sizeof(cliaddr)); printf("发送全更新失败...\n"); sleep(10); continue; } sleep(1); g_CMD = SOCK_CMD_HB; continue; case SOCK_CMD_HB: // 发送心跳 if((sock_serv_fd = sock_conn_server(&cliaddr, &conn_serv))<0) continue; protocol_CSHB_ready(); if( !CServer_send(sock_serv_fd, (u8 *)&CS_HB, sizeof(CS_HB))){ printf("发送心跳失败...\n"); sock_close(sock_serv_fd); memset(&cliaddr, 0, sizeof(cliaddr)); sleep(2); } sleep(300); break; } // switch } // while(1) of conn server } }
// socket to server SOCKET NetThread::socketToServer() { SOCKET sock = INVALID_SOCKET; ADDRINFO *addrinfo; ADDRINFO addrinfo_hints; memset(&addrinfo_hints, 0, sizeof(ADDRINFO)); #if 0 // for TEST addrinfo_hints.ai_family = AF_INET; // for IP v4 #else // for TEST addrinfo_hints.ai_family = AF_UNSPEC; #endif // for TEST addrinfo_hints.ai_socktype = SOCK_STREAM; char server[512]; char port[16]; int error; int result; result = snprintf(server, 256, "%s", qPrintable(settings->getServerName())); if (result <= 0 || result > 255){ if (settings->getOutputLog()){ const QString text = QString("socketToServer() : snprintf() error! for server"); emit outputLogMessage(PHASE_DEBUG, text); } return INVALID_SOCKET; } result = snprintf(port, 10, "%d", settings->getPortNo()); if (result <= 0 || result > 9){ if (settings->getOutputLog()){ const QString text = QString("socketToServer() : snprintf() error! for port"); emit outputLogMessage(PHASE_DEBUG, text); } return INVALID_SOCKET; } error = getaddrinfo(server, port, &addrinfo_hints, &addrinfo); if (error != 0){ #if defined(QTB_NET_WIN) if (settings->getOutputLog()){ const QString text = QString("socketToServer() : getaddrinfo(): error = ") + QString::number(error); emit outputLogMessage(PHASE_DEBUG, text); } #elif defined(QTB_NET_UNIX) if (settings->getOutputLog()){ const QString text = QString("socketToServer() : getaddrinfo(): strerror = ") + gai_strerror(error); emit outputLogMessage(PHASE_DEBUG, text); } #endif // defined(QTB_NET_UNIX) return INVALID_SOCKET; } ADDRINFO *topAddrinfo = addrinfo; for (; addrinfo != NULL; addrinfo = addrinfo->ai_next){ #if !defined(Q_OS_WIN) // Portable Vresion (for MacOSX, FreeBSD...) sock = connect_retry(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol, addrinfo->ai_addr, (int)addrinfo->ai_addrlen); if (sock == INVALID_SOCKET){ continue; } #else sock = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol); if (sock == INVALID_SOCKET){ continue; } if (connect_retry(sock, addrinfo->ai_addr, (int)addrinfo->ai_addrlen) == SOCKET_ERROR){ closesocket(sock); sock = INVALID_SOCKET; continue; } #endif break; } // free all addrinfo while(topAddrinfo != NULL){ addrinfo = topAddrinfo; topAddrinfo = addrinfo->ai_next; freeaddrinfo(addrinfo); } // for socket option if (sock != INVALID_SOCKET){ // set socket option setSocketOption(sock); // check socket option if (outputLog) checkSocketOption(sock); } else { // INVALID_SOCKET if (settings->getOutputLog()){ const QString text = "socketToServer() : sock = INVALID_SOCKET"; emit outputLogMessage(PHASE_DEBUG, text); } } return sock; }
int main(int argc, char *argv[]) { int fd, sfd, err, c; struct stat sbuf; char *host, *file; struct addrinfo *ailist, *aip; char *orient; long jobid; int text; int sides; /* 0=default 1=one-sided */ /* 2=two-sided-long-edge 3=two-sided-short-edge */ sides = 0; text = 0; err = 0; jobid = -1; while ((c = getopt(argc, argv, "is:to:c:h")) != -1) { switch (c) { case 'h': usage(); exit(0); case 'c': jobid = atol(optarg); break; case 'i': job_status(); exit(0); case 's': sides = atol(optarg); if (sides < 1 || sides > 3) err_sys("print: invalid sides option"); break; case 'o': orient = optarg; break; case 't': text = 1; break; case '?': err = 1; break; } } if (err || (optind != argc - 1)) err_quit("usage: print [-t] filename"); file = argv[optind]; if ((fd = open(file, O_RDONLY)) < 0) err_sys("print: can't open %s", file); if (fstat(fd, &sbuf) < 0) err_sys("print: can't stat %s", file); if (!S_ISREG(sbuf.st_mode)) err_quit("print: %s must be a regular file", file); /* * Get the hostname of the host acting as the print server. */ if ((host = get_printserver()) == NULL) err_quit("print: no print server defined"); if ((err = getaddrlist(host, "print", &ailist)) != 0) err_quit("print: getaddrinfo error: %s", gai_strerror(err)); for (aip = ailist; aip != NULL; aip = aip->ai_next) { if ((sfd = connect_retry(AF_INET, SOCK_STREAM, 0, aip->ai_addr, aip->ai_addrlen)) < 0) { err = errno; } else { if (jobid != -1) /* cancel job */ cancel_job(sfd, jobid); else submit_file(fd, sfd, file, sbuf.st_size, text, orient, sides); exit(0); } } err_exit(err, "print: can't contact %s", host); }