int test_miscellany_net() { unsigned char mac_addr[6]; char ip_addr[100]; #if 0 get_mac((char *)"eth0",mac_addr, sizeof(mac_addr)); print_mac(mac_addr); get_local_ip((char *)"eth0",ip_addr); print_ipaddr(ip_addr); set_local_ip((char *)"eth0","192.168.20.182"); get_local_ip((char *)"eth0",ip_addr); print_ipaddr(ip_addr); dbg_str(DBG_DETAIL,"get local netmask"); get_local_netmask((char *)"eth0",ip_addr); print_ipaddr(ip_addr); dbg_str(DBG_DETAIL,"set local netmask"); set_local_netmask((char *)"eth0",(char *)"255.255.255.0"); get_local_netmask((char *)"eth0",ip_addr); print_ipaddr(ip_addr); dbg_str(DBG_DETAIL,"ip and str convert"); inet_str2num(AF_INET,(char *)"192.168.20.2"); inet_num2str(AF_INET,34908352,ip_addr); #endif #if 0 if(inet_is_in_same_subnet("192.168.2.32","eth0")) { /* *dbg_str(DBG_DETAIL,"this ip addr add local addr is in the same net"); */ } else { dbg_str(DBG_DETAIL,"this ip addr add local addr is not in the same net"); } #endif get_broadcast_addr("eth0", ip_addr); print_ipaddr(ip_addr); /* *char ip_addr2[100]; *set_broadcast_addr("eth0", "192.168.20.255"); *print_ipaddr(ip_addr2); */ return 0; }
int tcp_client(unsigned int port) { int sockfd; if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) ERR_EXIT("socket"); if(port > 0) { int on = 1; if((setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on))) == -1) ERR_EXIT("setsockopt"); struct sockaddr_in addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); char ip[16] = {0}; get_local_ip(ip); addr.sin_addr.s_addr = inet_addr(ip); if(bind(sockfd, (struct sockaddr *)&addr, sizeof addr) == -1) ERR_EXIT("bind"); } return sockfd; }
int inet_is_in_same_subnet(char *ip_str,char *net_if_name) { char ip_addr[50]; char net_mask_addr[50]; uint32_t ip1, ip2, net_mask; get_local_ip(net_if_name,ip_addr); ip1 = inet_str2num(AF_INET,ip_addr); ip2 = inet_str2num(AF_INET,ip_str); /* *dbg_str(DBG_DETAIL,"ip=%x",ip2); */ get_local_netmask(net_if_name,net_mask_addr); /* *print_ipaddr(net_mask_addr); */ net_mask = inet_str2num(AF_INET,net_mask_addr); /* *dbg_str(DBG_DETAIL,"net_mask=%x",net_mask); */ if((ip1 & net_mask) == (ip2 & net_mask)) { return 1; } else { return 0; } }
void test_local_and_broadcast_ip() { char *local, *broadcast; get_local_ip(&local, NULL); get_broadcast_ip(&broadcast, NULL); printf("local=%s, broadcast=%s\n", local, broadcast); get_local_ip(&local, "vnic0"); get_broadcast_ip(&broadcast, "vnic0"); printf("interface (vnic0) local=%s, broadcast=%s\n", local, broadcast); get_local_ip(&local, "lo0"); get_broadcast_ip(&broadcast, "lo0"); printf("interface (lo0) local=%s, broadcast=%s\n", local, broadcast); get_local_ip(&local, "bob"); get_broadcast_ip(&broadcast, "bob"); printf("interface (bob) local=%s, broadcast=%s\n", local, broadcast); }
void get_master_ranks(std::set<size_t>& master_ranks) { uint32_t local_ip = get_local_ip(); std::vector<uint32_t> all_ips; all_gather(local_ip, all_ips); std::set<uint32_t> visited_ips; master_ranks.clear(); for(size_t i = 0; i < all_ips.size(); ++i) { if(visited_ips.count(all_ips[i]) == 0) { visited_ips.insert(all_ips[i]); master_ranks.insert(i); } } }
struct pkt_info_t init_and_connect(char *host, char *port) { struct pkt_info_t ret; memset(&ret, 0x00, sizeof(struct pkt_info_t)); char *device = get_device(); printf("Got interface: %s\n", device); ret.fd = init_socket(device); printf("Got socket\n"); ret.p_src_ip = get_local_ip(device); printf("Got local IP: %s\n", ret.p_src_ip); ret.p_dst_ip = get_peer_ip(host, port); register int i; for (i = 0; i < ret.p_dst_ip[0]->total; i++) printf("Got peer IP #%d: %s\n", i, ret.p_dst_ip[i]->d_ip); ret.p_src_port = ((arc4random() % 32768) + 32768); printf("Got local port: %d\n", ret.p_src_port); ret.p_dst_port = atoi(port); printf("Got peer port: %d\n", ret.p_dst_port); struct ether_header *eh = uni_get_mac(ret.fd, ret.p_dst_ip[0]->d_ip, port); memcpy(ret.p_src_mac, eh->ether_shost, ETH_ALEN); memcpy(ret.p_dst_mac, eh->ether_dhost, ETH_ALEN); printf("Got local MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", eh->ether_shost[0], eh->ether_shost[1], eh->ether_shost[2], eh->ether_shost[3], eh->ether_shost[4], eh->ether_shost[5]); printf("Got peer MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", eh->ether_dhost[0], eh->ether_dhost[1], eh->ether_dhost[2], eh->ether_dhost[3], eh->ether_dhost[4], eh->ether_dhost[5]); return ret; }
int wccp_add_webcache_id_component(struct wccp2_message_header *wccp2_msg_header){ struct wccp_webcache_id_info *wccp2_webcache_id_component; wccp2_webcache_id_component = (char *)wccp2_msg_header + get_wccp_message_length(wccp2_msg_header); wccp2_webcache_id_component->type = htons(WCCP2_WC_ID_INFO); wccp2_webcache_id_component->length = htons(44); wccp2_webcache_id_component->cache_ip = get_local_ip(); wccp2_webcache_id_component->hash_revision = htons(0x00); wccp2_webcache_id_component->weight = 0; wccp2_webcache_id_component->status = 0; update_wccp_message_length(wccp2_msg_header, wccp2_webcache_id_component->length); return 0; }
main () { init_socket(); get_local_ip(server_ip); while (1) { if (get_request_msg()) { send_offer_msg(); } sleep(1); } }
static void prepare_lisp_request (server *srv, handler_ctx *hctx) { size_t i; buffer *buf; connection *con = hctx->connection; chunkqueue *hr_cq = hctx->request_queue; buf = chunkqueue_get_append_buffer(hr_cq); #define APPEND_HEADER(k, vt, v) \ BUFFER_APPEND_STRING_CONST(buf, k); \ BUFFER_APPEND_STRING_CONST(buf, "\n"); \ buffer_append_##vt(buf, v); \ BUFFER_APPEND_STRING_CONST(buf, "\n") #define KEY_IS(string) \ (buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN(string)) == 0) #if 0 for (i = 0; i < srv->srv_sockets.used; i++) { log_error_write(srv, __FILE__, __LINE__, "sd<S>", "srv_sockets", i, inet_ntop_cache_get_ip(srv, &(srv->srv_sockets.ptr[i]->addr))); } #endif /* Mod_lisp configuration and connection info. */ APPEND_HEADER("server-id", string_buffer, hctx->socket_data->id); APPEND_HEADER("server-baseversion", string, PACKAGE_STRING); APPEND_HEADER("modlisp-version", string, MOD_LISP_VERSION); /* Server/connection configuration info. */ APPEND_HEADER("url", string_buffer, con->request.uri); APPEND_HEADER("method", string, get_http_method_name(con->request.http_method)); APPEND_HEADER("script-filename", string_buffer, con->physical.path); APPEND_HEADER("server-protocol", string, get_http_version_name(con->request.http_version)); APPEND_HEADER("remote-ip-port", long, get_remote_port(srv, con)); APPEND_HEADER("server-ip-port", long, srv->srvconf.port); APPEND_HEADER("remote-ip-addr", string, inet_ntop_cache_get_ip(srv, &(con->dst_addr))); APPEND_HEADER("server-ip-addr", string, get_local_ip(srv, con)); if (con->request.http_content_type) { APPEND_HEADER("content-type", string, con->request.http_content_type); } if (con->request.content_length) { APPEND_HEADER("content-length", long, con->request.content_length); }
void distributed_control::sync_ip_list() { // get the local IP char localip[4]; get_local_ip(localip); struct in_addr* localipinaddr = (struct in_addr*)(localip); logger(LOG_INFO, "Local IP = %s", inet_ntoa(*localipinaddr)); // build the gather op for all addresses all_addrs = new uint32_t[numprocs()]; MPI_Allgather(localip, 4, MPI_CHAR, all_addrs , 4, MPI_CHAR, MPI_COMM_WORLD); for (procid_t i = 0;i < numprocs(); ++i) { logger(LOG_INFO, "Node %d IP = %s",i, inet_ntoa(*(struct in_addr*)&(all_addrs[i]))); } localport = DC_LOCAL_BASE_PORT_NUM + procid(); }
int tcp_client(uint16_t port) { int peerfd = socket(AF_INET, SOCK_STREAM, 0); if (peerfd == -1) ERR_EXIT("socket"); if (port == 0) return peerfd; SAI addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(get_local_ip()); if (bind(peerfd, (SA *)&addr, sizeof addr) == -1) ERR_EXIT("bind"); return peerfd; }
//这个函数返回本机的节点ID //如果不能获取本机的节点ID, 返回-1. int topology_getMyNodeID() { //printf("In topology_getMyNodeID "); if (myNodeId == 0) { // hasn't know myNodeId struct in_addr ip; ip.s_addr = get_local_ip(); if( ip.s_addr != 0) { myNodeId = topology_getNodeIDfromip(&ip); return myNodeId; } else return -1; } //printf("return myNodeId: %d\n", myNodeId); return myNodeId; }
int main(int argc, char** argv) { printf("test 1\n"); initialize_default_ip_lookup_urls(); int num_lookup_urls; for(num_lookup_urls=0; default_ip_lookup_urls[num_lookup_urls][0] != '\0'; num_lookup_urls++); printf("num lookup urls = %d\n", num_lookup_urls); int i; for(i=0; i < num_lookup_urls; i++) { char* ip = get_local_ip(INTERNET, NULL); printf("ip = %s\n", ip); } return 0; }
int main(int argc, const char *argv[]) { char ip[36] = {0}; char mac[36] = {0}; #if 1 char hostname[256]; struct hostent *get_host_by_name; if (gethostname(hostname, sizeof(hostname)) != 0) { printf("Can not get hostname\n"); exit(1); } get_host_by_name = gethostbyname(hostname); if ((strcpy(ip, (char *)inet_ntoa(*(struct in_addr*)(get_host_by_name->h_addr_list[0])))) == NULL) { printf("Can not get loacl ip\n"); exit(1); } else { printf("hostname: %s\n",hostname); printf("local ip: %s\n",ip); } #endif if (get_local_ip(ip, mac) == 0) //if (get_local_ip(ip, NULL) == 0) //if (get_local_ip(NULL, mac) == 0) { printf("local ip: %s\n",ip); printf("local mac: %s\n",mac); } else { printf("Can not get loacl ip\n"); } return 0; }
//这个函数连接到本地SIP进程的端口SIP_PORT. 如果TCP连接失败, 返回-1. 连接成功, 返回TCP套接字描述符, STCP将使用该描述符发送段. int connectToSIP() { struct sockaddr_in servaddr; int sockfd = socket(AF_INET, SOCK_STREAM, 0); //AF_INET for ipv4; SOCK_STREAM for byte stream if(sockfd < 0) { printf("Socket error!\n"); return 0; } memset(&servaddr, 0, sizeof(struct sockaddr_in)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = get_local_ip(); servaddr.sin_port = htons(SIP_PORT); //connect to the server if(connect(sockfd, (struct sockaddr* )&servaddr, sizeof(servaddr)) < 0) {//创建套接字连接服务器 printf("Link to SIP Wrong!\n"); exit(1); } else printf("Link to SIP Success!\n"); return sockfd; }
const char* socket_stream::get_local(bool full /* = false */) const { if (stream_ == NULL) return dummy_; // xxx: acl_vstream 中没有对此地址赋值 char* ptr = ACL_VSTREAM_LOCAL(stream_); if (ptr == NULL || *ptr == 0) { char buf[256]; if (acl_getsockname(ACL_VSTREAM_SOCK(stream_), buf, sizeof(buf)) == -1) { return dummy_; } acl_vstream_set_local(stream_, buf); } if (full) return ACL_VSTREAM_LOCAL(stream_); else return get_local_ip(); }
int main(int argc, const char *argv[]) { sqlite3 *db; char *err = 0; int ret = 0; char buf[4096]; char value[4096]; char *p = NULL; char *q = NULL; int len = 0; int reg = 0; int log = 0; int login_flag = 0; char *confirm; char ip[36] = {0}; printf("Content-Type: text/html\n\n"); while((ret = fread(buf, 1, sizeof(buf), stdin)) != 0) { //printf("read %d len\n", ret); //printf("%s", buf); } if (get_local_ip(ip, NULL) != 0) { printf("Server is unavailable\n"); exit(1); } if ((p = strstr(buf, "=Register")) != NULL) { reg = 1; p -= 4; *p = '\0'; q = strstr(buf, "&confirm="); *q = '\0'; confirm = q + 9; } if ((p = strstr(buf, "&log=Login")) != NULL) { log = 1; *p = '\0'; } //username=sd&password=sdd&confirm=dsssd®=Register p = strchr(buf, '='); p++; q = strchr(buf, '&'); if (p == q) { send_html(0, 0, "Blank username!"); if (reg == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); } if (log == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/index.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/index.html\">",ip); } return 0; } *q = '\0'; //username=ab&password=ab&confirm=ab®=Register if (strchr(p, '+') != NULL) { send_html(0, 0, "Username can not have blank space !"); if (reg == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); } if (log == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/admin_login.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/index.html\">",ip); } return 0; } if ((len = strlen(p)) > 20) { send_html(0, 0, "Username is overlength !"); if (reg == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); } if (log == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/admin_login.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/index.html\">",ip); } return 0; } str.username = p; q += 10; if (*q == '\0' || *q == '&') { send_html(0, 0, "Blank password !"); if (reg == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); } if (log == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/admin_login.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/index.html\">",ip); } return 0; } /* if ((p = strstr(q, "®=Register")) != NULL) { reg = 1; *p = '\0'; } if ((p = strstr(q, "&log=Login")) != NULL) { log = 1; *p = '\0'; } */ if ((len = strlen(q)) > 20) { printf("\n%s\n",q); send_html(0, 0, "Password is overlength !"); if (reg == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); } if (log == 1) { //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/admin_login.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/index.html\">",ip); } return 0; } str.password = q; #if 1 if (reg == 1) { if (strcmp(str.password, confirm) != 0) { send_html(0, 0, "Confirm password not match !"); //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); return 0; } } #endif ret = sqlite3_open("./admin_login.db", &db); if (ret != SQLITE_OK) { fputs(sqlite3_errmsg(db), stderr); fputs("\n", stderr); exit(1); } if (reg == 1) { //sprintf(value, "select username='******', username, password from register_info;", str.username); sprintf(value, "select * from register_info where username='******';", str.username); //ret = sqlite3_exec(db, "select * from register_info", rscallback_register, &login_flag, &err); ret = sqlite3_exec(db, value, rscallback_register, &login_flag, &err); if (login_flag == 1) { sqlite3_close(db); send_html(0, 0, "Reduplicated username !"); send_html(0, 0, "Please input your username again !"); //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/register.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/register.html\">",ip); return 0; } sprintf(value, "insert into register_info(username, password) values('%s', '%s');", str.username, str.password); ret = sqlite3_exec(db, value, NULL, NULL, &err); } if (log == 1) { //sprintf(value, "select username='******', username, password from register_info;", str.username); sprintf(value, "select * from register_info where username='******' and password='******';", str.username, str.password); ret = sqlite3_exec(db, value, rscallback_login, &login_flag, &err); //ret = sqlite3_exec(db, "select * from register_info", rscallback_login, &login_flag, &err); } if (ret != SQLITE_OK) { fputs(err, stderr); fputs("\n", stderr); sqlite3_close(db); if (reg == 1) { printf("\nRegister failure !\n"); } if (log == 1) { printf("\nLogin failure !\n"); } exit(1); } sqlite3_close(db); if (reg == 1) { send_html(0, 0, "Register succesfully !"); send_html(0, 0, "Turning into administration system..."); //printf("<meta http-equiv=\"refresh\"content=\"1; url=http://192.168.11.252/administration.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/administration.html\">",ip); } if (log == 1) { if (login_flag == 1) { send_html(0, 0, "Login succesfully !"); send_html(0, 0, "Turning into administration system..."); //printf("<meta http-equiv=\"refresh\"content=\"1; url=http://192.168.11.252/administration.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/administration.html\">",ip); } else { send_html(0, 0, "Username or password wrong, please input again !"); //printf("<meta http-equiv=\"refresh\"content=\"2; url=http://192.168.11.252/index.html\">"); printf("<meta http-equiv=\"refresh\"content=\"2; url=http://%s/index.html\">",ip); } } return 0; }
int main(int argc, char *argv[]) { int len = 0; char buffer[4096]; socklen_t client_len; int server_sock; struct sockaddr_in server, client; struct in_addr in; int server_sock_tcp; int client_sock_tcp; struct sockaddr_in server_tcp,client_tcp; char ip[36] = {0}; char mac[36] = {0}; char *receive_ip = NULL; char *receive_mac = NULL; char *p = NULL; get_ip_mac: if (get_local_ip(ip, mac) == 0) { printf("local ip: %s\n",ip); printf("local mac: %s\n",mac); } else { printf("Can not get loacl ip\n"); sleep(3); goto get_ip_mac; } start: if ((server_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } else { printf_debug("UDP create socket ok !\n"); } int optval = 1; bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(SERVER_PORT); server.sin_addr.s_addr = htons(INADDR_ANY); //server.sin_addr.s_addr = inet_addr("255.255.255.255"); setsockopt(server_sock, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)); //setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (bind(server_sock, (struct sockaddr *)&server, sizeof(server)) < 0) { fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } else { printf_debug("UDP bind addr ok !\n\n"); } printf("Wait to update ...\n"); again: client_len = sizeof(client); len = recvfrom(server_sock, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client, &client_len); printf_debug("--- %s ---\n", buffer); if (len < 0) { close(server_sock); fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } //if ((strcmp(buffer, "ready1") != 0) && (strcmp(buffer, "readyall") != 0)) //goto again; if (strcmp(buffer, "readyall") != 0) { if (strcmp(buffer, "heartbeat") == 0) { printf("heartbeat\n"); sprintf(buffer, "heartbeat@%s@%s",ip, mac); client_len = sizeof(client); if (sendto(server_sock, buffer, BUFFER_SIZE, 0,(struct sockaddr *)&client ,client_len) < 0) { printf("-----------------send heartbeat failed\n"); close(server_sock); goto start; } goto again; } #if 1 else { p = buffer; while (*p != '\0') { if (*p == '@') { *p = '\0'; receive_ip = buffer; receive_mac = p + 1; if ((strcmp(ip, receive_ip) == 0) && (strcmp(mac, receive_mac) == 0)) { //printf_debug("ip: %s\n",ip); //printf_debug("receive_ip: %s\n",receive_ip); //printf_debug("mac: %s\n",mac); //printf_debug("receive_mac: %s\n",receive_mac); break; } goto again; } p++; } } #endif } //TCP #if 1 if ((server_sock_tcp = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } else { printf_debug("TCP create socket ok!\n"); } int on = 1; setsockopt(server_sock_tcp, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); bzero(&server_tcp, sizeof(server_tcp)); server_tcp.sin_family = AF_INET; server_tcp.sin_port = htons(SERVER_PORT_TCP); server_tcp.sin_addr.s_addr = htons(INADDR_ANY); if(bind(server_sock_tcp, (struct sockaddr *)&server_tcp, sizeof(server_tcp)) < 0) { fprintf(stderr, "%s\n", strerror(errno)); printf("tcp bind error !\n"); exit(EXIT_FAILURE); } else { printf_debug("TCP bind addr ok!\n"); } if(listen(server_sock_tcp, 5) < 0) { fprintf(stderr, "%s\n", strerror(errno)); exit(EXIT_FAILURE); } else { printf_debug("TCP listen ok!\n"); } #endif #if 0 //delete files and ready to sync DIR *dir; struct dirent *ptr; int i = 0; int iret = 0; for (i = 0; i < 4; i++) { sprintf(buffer, "%s/%s", PATH_HOME, *(filename + i)); if ((dir = opendir(buffer)) != NULL) { while ((ptr = readdir(dir)) != NULL) { if (ptr->d_type == DT_REG) { sprintf(buffer, "%s/%s/%s",PATH_HOME, *(filename + i), ptr->d_name); printf_debug("path: %s\n",buffer); if ((iret = remove(buffer)) < 0) { printf("fail to delete %s \n",ptr->d_name); } printf("delete one file\n"); } } } } #endif //UDP //sleep(3); printf_debug("UDP Connect client successfully !\n"); client_len = sizeof(client); strcpy(buffer, "ready to sync"); //if (sendto(server_sock, "ready to sync", strlen("ready to sync"), 0,(struct sockaddr *)&client ,client_len) < 0) //if (sendto(server_sock, "ready to sync", BUFFER_SIZE, 0,(struct sockaddr *)&client ,client_len) < 0) //if (sendto(server_sock, "ready to sync", 13, 0,(struct sockaddr *)&client ,client_len) < 0) if (sendto(server_sock, buffer, BUFFER_SIZE, 0,(struct sockaddr *)&client ,client_len) < 0) { printf("-----------------ready to sync failed\n"); close(server_sock_tcp); close(server_sock); goto start; } #if 0 if (pthread_create(&tid, NULL, pthread, NULL) != 0) { printf("can't create thread"); //close(server_sock); //close(server_sock_tcp); //system("./TS1500DC_update.bin"); exit(1); } #endif #if 0 int flag_block; int connected = 0; flag_block = fcntl(server_sock_tcp, F_GETFL, 0); flag_block |= O_NONBLOCK; fcntl(server_sock_tcp, F_SETFL, flag_block);//设置非阻塞 client_sock_tcp = accept(server_sock_tcp, (struct sockaddr *)&client_tcp, &client_len); //if((client_sock_tcp = accept(server_sock_tcp, (struct sockaddr *)&client_tcp, &client_len)) < 0) #if 0 if (connected != 0) if(errno != EINPROGRESS) { printf("<h2>Update failed !<br><h2>\n"); goto tcp_end; } else //esle #endif { struct timeval tm; tm.tv_sec = 60; tm.tv_usec = 0; fd_set set,rset; FD_ZERO(&set); FD_ZERO(&rset); FD_SET(server_sock_tcp, &set); FD_SET(server_sock_tcp, &rset); int res; res = select(server_sock_tcp+1, &rset,&set, NULL, &tm); if(res < 0) { printf("<h2>Network error in connect, update failed !<br><h2>\n"); goto tcp_end; } else if(res == 0) { printf("<h2>Connect time out, update failed !<br><h2>\n"); //printf_debug("client port: %d\n", ntohs(client_tcp.sin_port)); goto tcp_end; } else if (res == 1) { if(FD_ISSET(server_sock_tcp, &set)) { flag_block &= ~O_NONBLOCK; fcntl(server_sock_tcp, F_SETFL, flag_block);//设置阻塞 fd_now = NULL; flag = 0; int length = 0; memset(buffer, 0, sizeof(buffer)); while ((length = recv(client_sock_tcp, buffer, BUFFER_SIZE, 0)) > 0) { while (length != BUFFER_SIZE) { length += recv(client_sock_tcp, buffer + length, BUFFER_SIZE-length, 0); } len = ((buffer[2] << 8)&0xff00) + buffer[3]; //printf_debug("%s\n",buffer + 4); #if 1 switch(buffer[0]) { case '0': received_file(buffer, len, PATH_HOME); break; case '1': received_file(buffer, len, PATH_HOME); break; case '2': received_file(buffer, len, PATH_HOME); break; case '3': received_file(buffer, len, PATH_HOME); #if 0 if (buffer[1] == '1') { //if (fd != NULL) //fclose(fd); strcpy(path, "./upload-folder/OtherFile"); iret = access(path, W_OK); if(iret != 0) { iret = mkdir(path, 0777); if(iret != 0) { printf("can not create dir"); exit(1); } } strcat(path, "/"); strcat(path, (buffer + 4)); fd = fopen(path, "w+"); if(fd == NULL) { printf("can not open file"); exit(1); } printf("%s",(buffer + 4)); } if (buffer[1] == '0') { len = fwrite(buffer + 4, 1, len-4, fd); printf("write len = %d\n",len); } #endif break; default : break; } #endif } if (fd_now != NULL) { fclose(fd_now); } flag = 0; fd_before = NULL; printf("\nUpdate finished\n\n"); } else { fprintf(stderr, "%s\n", strerror(errno)); printf("<h2>Other error, update failed !<br><h2>\n"); goto tcp_end; } } } #else //TCP //int nTimeOut = 10; //setsockopt(server_sock_tcp, SOL_SOCKET, SO_RCVTIMEO, (char *)&nTimeOut, sizeof(nTimeOut)); client_len = sizeof(client_tcp); if((client_sock_tcp = accept(server_sock_tcp, (struct sockaddr *)&client_tcp, &client_len)) < 0) { fprintf(stderr, "%s\n", strerror(errno)); goto tcp_end; //exit(EXIT_FAILURE); } else { printf_debug("accept client ok!\n"); //in.s_addr = client_tcp.sin_addr.s_addr; //printf_debug("client ip : %s\n", inet_ntoa(in)); //printf_debug("client port: %d\n", ntohs(client_tcp.sin_port)); } fd_now = NULL; flag = 0; int length = 0; memset(buffer, 0, sizeof(buffer)); while ((length = recv(client_sock_tcp, buffer, BUFFER_SIZE, 0)) > 0) { while (length != BUFFER_SIZE) { length += recv(client_sock_tcp, buffer + length, BUFFER_SIZE-length, 0); } len = ((buffer[2] << 8)&0xff00) + buffer[3]; //printf_debug("%s\n",buffer + 4); switch(buffer[0]) { case '0': received_file(buffer, len, PATH_HOME); break; case '1': received_file(buffer, len, PATH_HOME); break; case '2': received_file(buffer, len, PATH_HOME); break; case '3': received_file(buffer, len, PATH_HOME); #if 0 if (buffer[1] == '1') { //if (fd != NULL) //fclose(fd); strcpy(path, "./upload-folder/OtherFile"); iret = access(path, W_OK); if(iret != 0) { iret = mkdir(path, 0777); if(iret != 0) { printf("can not create dir"); exit(1); } } strcat(path, "/"); strcat(path, (buffer + 4)); fd = fopen(path, "w+"); if(fd == NULL) { printf("can not open file"); exit(1); } printf("%s",(buffer + 4)); } if (buffer[1] == '0') { len = fwrite(buffer + 4, 1, len-4, fd); printf("write len = %d\n",len); } #endif break; default : break; } } if (fd_now != NULL) { fclose(fd_now); } flag = 0; fd_before = NULL; printf("\nUpdate finished\n\n"); #endif tcp_end: close(server_sock_tcp); close(server_sock); goto start; exit(EXIT_SUCCESS); }
static int load_conf_from_file(const char *filename) { char buf[MAX_LINE_NUM]; char ip[MAX_LINE_NUM]; char *p = NULL; char *key = NULL, *value = NULL; if(!filename) { return -1; } FILE *fs = fopen(filename, "rt"); if(!fs) { RTE_ERR("%s(%d), can not open configue file, file:%s\n", __FUNCTION__, __LINE__, filename); return -1; } while((p = fgets(buf, MAX_LINE_NUM, fs)) != NULL) { if(*p == '#' || *(p + 1) == '#') continue; RTE_DBG("%s(%d), Read new line:%s\n", __FUNCTION__, __LINE__, buf); key = p; value = strchr(p, '='); if(!value) continue; if(strncmp(key, "mgt_device", 10) == 0) { p = strchr(value, '\n'); if(p) { *p = '\0'; } value = strchr(value, '"'); if(value) { value++; p = strchr(value, '"'); if(p) { *p = '\0'; } } if(get_local_ip(value, ip) < 0) { continue; } sprintf(buf, "set_localip,%s", ip); execute_app_request(buf, strlen(buf)); } else if(strncmp(key, "enableL2CT", 10) == 0) { int flag = (int)strtoul(value + 1, NULL, 10); if(flag) { set_flags_l2ct_enable(); } else { clear_flags_l2ct_enable(); } } else if(strncmp(key, "enableDPI", 9) == 0) { int flag = (int)strtoul(value + 1, NULL, 10); if(flag) { set_flags_dpi_enable(); } else { clear_flags_dpi_enable(); } } else if(strncmp(key, "enableTC", 8) == 0) { int flag = (int)strtoul(value + 1, NULL, 10); if(flag) { set_flags_tc_enable(); } else { clear_flags_tc_enable(); } } else if(strncmp(key, "enableOFO", 9) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); if(flag) { set_flags_ofo_enable(flag); } } else if(strncmp(key, "enableDynamic", 13) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); if(flag) { set_flags_dynamic_enable(flag); } } else if(strncmp(key, "hashBucketSize", 14) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); if(flag) { set_hash_size(flag); } } else if(strncmp(key, "enableDumpPcapFlag", 18) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); pcap_dump_control_flag = flag; } else if(strncmp(key, "dumpPcapFileSize", 16) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); pcap_dump_file_size = flag; } else if(strncmp(key, "dumpPcapPacketNum", 17) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); pcap_dump_packet_num = flag; } else if(strncmp(key, "dumpPcapSpecialFlag", 19) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); pcap_dump_special_flag = flag; } else if(strncmp(key, "dumpPcapSpecialProtoMark", 24) == 0) { uint64_t flag = (int)strtoul(value + 1, NULL, 10); pcap_dump_special_proto_mark = flag; } } fclose(fs); return 0; }
int main(void *arg) { int ret = -1; int sock = -1; struct Device_Info device; unsigned char *ptr = NULL; struct sockaddr_in local_addr; struct sockaddr_in from_addr; int from_len = sizeof(struct sockaddr_in); int count = -1; fd_set readfd; char buff[BUFFER_LEN]; struct timeval timeout; timeout.tv_sec = 2; timeout.tv_usec = 0; memset(device.device_ip, 0, sizeof(device.device_ip)); memset(device.device_mac, 0, sizeof(device.device_mac)); memset(device.device_num, 0, sizeof(device.device_num)); memset(device.info, 0, sizeof(device.info)); memcpy(device.device_ip, get_local_ip(), 20); memcpy(device.device_mac, get_local_mac(), 20); memcpy(device.device_num, "AG172", sizeof("AG172")); memcpy(device.info, MATCH_INFO, sizeof(MATCH_INFO)); sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock < 0 ) { printf("HandleIPFound: socket init error!\n"); return 0; } memset((void*)&local_addr, 0, sizeof(struct sockaddr_in)); local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = htonl(INADDR_ANY); local_addr.sin_port = htons(MCAST_PORT); printf("local IP is %s\n",inet_ntoa(local_addr.sin_addr)); ret = bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr)); if(ret != 0) { printf("HandleIPFound:bind error...\n"); return 0; } while(1) { FD_ZERO(&readfd); FD_SET(sock, &readfd); ret = select(sock+1, &readfd, NULL, NULL, &timeout); switch(ret) { case -1: break; case 0: break; default: if( FD_ISSET( sock, &readfd )) { memset(buff, 0, BUFFER_LEN); count = recvfrom(sock, buff, BUFFER_LEN, 0, (struct sockaddr*)&local_addr, &from_len); printf("Recv msg is %s,count=%d\n", buff, count); if( strstr(buff, IP_FOUND)) { // memcpy(buff, (char *)&device, strlen(device)); printf("Now buff is %s\n", buff); printf("local ip is %s\n", device.device_ip); printf("local mac is: %s\n", device.device_mac); // ptr = (unsigned char *)&device; count = sendto(sock, (struct Device_Info *)&device, sizeof(device), 0, (struct sockaddr*)&local_addr, from_len); //count = sendto(sock, ptr, sizeof(device), 0, (struct sockaddr*)&local_addr, from_len); printf("count = %d\n",count); } } } } return 0; }
int wccp_add_assignment_info_component(struct wccp_service_group *this_wccp_service_group, struct wccp2_message_header *wccp2_msg_header){ struct wccp_assignment_info *wccp_wccp_assignment_info_component = NULL; struct wccp_router_assignment_element *wccp_router_assignment = NULL; struct wccp_server *this_wccp_server = NULL; struct wccp_webcache *this_wccp_webcache = NULL; int i = 0; __u32 *num_routers = NULL; __u32 *num_webcaches = NULL; __u32 *webcacheip = NULL; char *buckets = NULL; wccp_wccp_assignment_info_component = (char *)wccp2_msg_header + get_wccp_message_length(wccp2_msg_header); wccp_wccp_assignment_info_component->type = htons(WCCP2_REDIRECT_ASSIGNMENT); wccp_wccp_assignment_info_component->assignment_key.key_ip_address = get_local_ip(); wccp_wccp_assignment_info_component->assignment_key.key_change_number = htonl(this_wccp_service_group->change_number); wccp_wccp_assignment_info_component->length = htons(8); /* * Next we list how many routers are in the service group and create their assignment elements. */ num_routers = (char *)wccp_wccp_assignment_info_component + 12; *num_routers = htonl(this_wccp_service_group->servers.count); wccp_wccp_assignment_info_component->length = htons(ntohs(wccp_wccp_assignment_info_component->length) + 4); wccp_router_assignment = (char *)num_routers + 4; this_wccp_server = this_wccp_service_group->servers.next; while(this_wccp_server != NULL){ wccp_router_assignment->router_id = this_wccp_server->ipaddress; wccp_router_assignment->receive_id = htonl(this_wccp_server->router_id + 1); wccp_router_assignment->change_number = htonl(this_wccp_service_group->change_number); wccp_wccp_assignment_info_component->length = htons(ntohs(wccp_wccp_assignment_info_component->length) + sizeof(struct wccp_router_assignment_element)); wccp_router_assignment = wccp_router_assignment + 1; this_wccp_server = this_wccp_server->servers.next; } /** * Next we enter the number of web-caches in the service group and list them by IP address. */ if(this_wccp_service_group->servers.count > 0){ num_webcaches = (char*)num_routers + 4 + (this_wccp_service_group->servers.count * sizeof(struct wccp_router_assignment_element)); }else{ num_webcaches = (char*)num_routers + 4; } *num_webcaches = htonl(this_wccp_service_group->webcaches.count); wccp_wccp_assignment_info_component->length = htons(ntohs(wccp_wccp_assignment_info_component->length) + 4); this_wccp_webcache = this_wccp_service_group->webcaches.next; webcacheip = (char*)num_webcaches + 4; while(this_wccp_webcache != NULL){ *webcacheip = this_wccp_webcache->ipaddress; wccp_wccp_assignment_info_component->length = htons(ntohs(wccp_wccp_assignment_info_component->length) + 4); webcacheip = webcacheip + 1; this_wccp_webcache = this_wccp_webcache->webcaches.next; } /* * Last we assign individual buckets to each web-cache. */ if(this_wccp_service_group->webcaches.count > 0){ buckets = (char *)num_webcaches + 4 + (this_wccp_service_group->webcaches.count * sizeof(__u32)); }else{ buckets = (char *)num_webcaches + 4; } for(i=0;i<256;i++){ buckets[i] = htons(0); //Just assign everything to web-cache 0 for now. } wccp_wccp_assignment_info_component->length = htons(ntohs(wccp_wccp_assignment_info_component->length) + 256); update_wccp_message_length(wccp2_msg_header, wccp_wccp_assignment_info_component->length); return 0; }
/********************************************************* ****************** Main Function ****************** *********************************************************/ int main(int agrc, char *agrv[]) { /** * cmd parameter */ int help_flag = 0; int ipv6_flag = 0; int ser_flag = 0; int cli_flag = 0; int ser_or_cli_flag = -1; int socket_protocol = -1; int socket_type = -1; int net_type = AF_INET; int times = 1; char *protocol = NULL; char *message = NULL; char *ip = NULL; int port = 0; int rt = 0; int local_ip_flag = 0; char local_ip[256] = {0}; int gateway_ip_flag = {0}; char gateway_ip[128] = {0}; char *ifname = NULL; unsigned char local_mac[6] = {0}; char *remote_mac = NULL; char remote_ip[20] = {0}; struct options opts[] = { {"-h", "--help" , 0, RET_INT, ADDR_ADDR(help_flag) }, {"-6", NULL , 0, RET_INT, ADDR_ADDR(ipv6_flag) }, {"-s", "--server" , 0, RET_INT, ADDR_ADDR(ser_flag) }, {"-c", "--client" , 0, RET_INT, ADDR_ADDR(cli_flag) }, {"-a", "--agreement" , 1, RET_STR, ADDR_ADDR(protocol) }, {"-i", "--ip" , 1, RET_STR, ADDR_ADDR(ip) }, {"-p", "--port" , 1, RET_INT, ADDR_ADDR(port) }, {"-t", "--times" , 1, RET_INT, ADDR_ADDR(times) }, {"-m", "--message" , 1, RET_STR, ADDR_ADDR(message) }, {"-l", "--localip" , 0, RET_INT, ADDR_ADDR(local_ip_flag) }, {"-g", "--gatewayip" , 0, RET_INT, ADDR_ADDR(gateway_ip_flag)}, {NULL, "--mac" , 1, RET_STR, ADDR_ADDR(ifname) }, {"-r", "--remoteip" , 1, RET_STR, ADDR_ADDR(remote_mac) }, {NULL, NULL} }; struct usage help_usage[] = { {"-s, --server", "Create a socket server"}, {"-c, --client", "Create a socket client"}, {"-a, --agreement [Agreement]", "Agreement of networking. Agreement can be \"[u udp t tcp]\""}, {"-i, --ip [ip address]", "IP address"}, {"-p, --port [port]", "Port"}, {"-t, --times [times]", "Times of sending message"}, {"-m, --message [message]", "Message of sending"}, {"-l, --localip", "Local ip address"}, {"-g, --gatewayip", "Gateway ip address"}, {"--mac [interface name]", "Get mac address by interface name."}, {"-r, --remoteip [mac address]", "Get remote ip address."}, {"-h, --help", "Program usage"}, {NULL, NULL} }; /** * check count of cmdline arguemnts */ set_print_usage_width(60); if (agrc <= 1) { print_usage(help_usage); exit(-1); } /** * parser args */ get_args(agrc, agrv, opts); if(help_flag > 0) { print_usage(help_usage); exit(1); } /** * get mac addree by interface name */ if (ifname) { if (get_mac(ifname, local_mac, sizeof(local_mac)) < 0) return -1; print_mac(local_mac, NULL); return 0; } /** * get remote ip address by mac address */ if (remote_mac) { if (get_remote_ip_by_mac(remote_mac, remote_ip, sizeof(remote_ip), 0) < 0) return -1; printf("%s\n", remote_ip); return 0; } /** * Get Local IP Address */ if (ipv6_flag > 0) net_type = AF_INET6; if (local_ip_flag) { if (get_local_ip(net_type, NULL, local_ip, sizeof(local_ip)) < 0) { exit(-1); } printf("%s\n", local_ip); exit(0); } /** * get gateway ip address */ if (gateway_ip_flag) { if (get_gateway(gateway_ip, sizeof(gateway_ip)) < 0) { exit(-1); } printf("%s\n", gateway_ip); exit(0); } /** * socket server or client */ if (ser_flag > 0) ser_or_cli_flag = SOCKET_SERVER; else if (cli_flag > 0) ser_or_cli_flag = SOCKET_CLIENT; /** * socket protocol */ if (protocol != NULL) { if (!strncmp("u", protocol, sizeof("u")) || !strncmp("udp", protocol, sizeof("udp"))) { socket_protocol = IPPROTO_UDP; socket_type = SOCK_DGRAM; } else if (!strncmp("t", protocol, sizeof("t")) || !strncmp("tcp", protocol, sizeof("tcp"))) { socket_protocol = IPPROTO_TCP; socket_type = SOCK_STREAM; } else { fprintf(stderr, "Invalid arguemnt\n"); exit(1); } } /** * start up socket */ start_network(ser_or_cli_flag, net_type, socket_type, socket_protocol, ip, port, times, message); return rt; }
int main(int argc, char *argv[]) { struct sockaddr_in server_addr; struct sockaddr_in client_addr; if(argc != 3) { printf("%s dst_ip dst_port\n", argv[0]); return 0; } int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock < 0) { printf("StreamSocket Create socket failed\n"); return -1; } int err = bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)) ; if(err < 0) { perror("bind()"); return -1; } printf("local ip 0x%x, port %d\n", get_local_ip(sock), get_local_port(sock)); /* char* dev = "eth1"; if (setsockopt (sock, SOL_SOCKET, SO_BINDTODEVICE, dev, sizeof("dev1")) < 0) { perror("Setting SO_REUSEADDR error"); close(sock); return -1; } */ memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(argv[1]);; server_addr.sin_port = htons(atoi(argv[2])); int ret; struct sockaddr_in addr; socklen_t addr_len; addr_len = sizeof(addr); ret = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (ret == -1) { perror("connect server fail:"); close(sock); return -1; } printf("connect success\n"); printf("local ip 0x%x, port %d\n", get_local_ip(sock), get_local_port(sock)); char *sbuf; struct test_proto ap = {0}; ap.addr = inet_addr("192.168.0.2"); ap.type = 100; ap.port = 2152; int len = sizeof(struct test_proto); sbuf = (char*)≈ write(sock, (char *)sbuf, len); sleep(10); close(sock); /* char buf[1024] = "shuwhude"; int len = 6;//sizeof(buf); while(1) { printf("local ip 0x%x, port %d\n", get_local_ip(sock), get_local_port(sock)); ret = write(sock, (char *)buf, len); if (ret < 0) { printf("write() failed. len = %d, ret = %d, errno = %d:%s\n", len, ret, errno, strerror(errno)); return -1; } sleep(1); memset(buf, 0, sizeof(buf)); ret = read(sock, (char *)buf, sizeof(buf)); if (ret < 0) { printf("read() failed. len = %d, ret = %d, errno = %d:%s\n", len, ret, errno, strerror(errno)); return -1; } else if(ret == 0) { printf("server bye\n"); close(sock); return 0; } else { sleep(1); buf[ret]='\0'; printf("recieve back buf: %s\n", buf); } //close(sock); } */ }
static void main_loop(const char *serverIp, Uint16 port) { int sockTcp = socket_tcp_server(56790, 5); assert(sockTcp >= 0); int sockUdp = socket_udp_server(56790); assert(sockUdp >= 0); int err = set_sock_send_timeout(sockTcp, 5); err |= set_sock_recv_timeout(sockTcp, 5); assert(err == 0); err = set_sock_buf_size(sockUdp, 512 * 1024, 512 * 1024); err |= set_sock_linger(sockUdp, TRUE, 2); err |= set_sock_block(sockUdp, FALSE); DBG("err = %d", err); assert(err == 0); close(sockTcp); close(sockUdp); sockTcp = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in addr; init_sock_addr(&addr, serverIp, port); err = connect_nonblock(sockTcp, (struct sockaddr *)&addr, sizeof(addr), 5000); if(err < 0) { ERR("Connect nonblocking server failed."); goto exit; } else { DBG("Connect to %s:%u success!", serverIp, port); } close(sockTcp); close(sockUdp); sockTcp = sockUdp = -1; sockTcp = socket(AF_INET, SOCK_STREAM, 0); err = connect(sockTcp, (struct sockaddr *)&addr, sizeof(addr)); if(err < 0) { ERR("Connect server failed."); goto exit; } else { DBG("Connect to %s:%u success!", serverIp, port); } sockUdp = socket(AF_INET, SOCK_DGRAM, 0); char *sendLine = "Hello"; err = sendto(sockUdp, sendLine, strlen(sendLine), 0, (struct sockaddr *)&addr, sizeof(addr)); if(err < 0) ERR("Send to failed."); else DBG("Sendto ok..."); char ipBuf[32]; err = get_local_ip(ipBuf, sizeof(ipBuf)); assert(err == E_NO); DBG("get local ip: %s", ipBuf); Uint8 macAddr[6]; err = sys_get_mac("eth0", macAddr, sizeof(macAddr)); assert(err == E_NO); DBG("get mac addr: %02X-%02X-%02X-%02X-%02X-%02X", macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]); exit: if(sockTcp > 0) close(sockTcp); if(sockUdp > 0) close(sockUdp); }
void *open_new_tcp_task(void *arg) { PRINTF("open_new_tcp_task is start\n"); int index = *(int *)arg; int serv_sockfd = -1, cli_sockfd; struct sockaddr_in serv_addr, cli_addr; int file_flag = -1; int len = 0; int opt = 1; int ipos = 0; int clientsocket = -1; int ret = 0; int ipaddr; PRINTF("open_new_tcp_task index:[%d]\n", index); sem_init((sem_t *)&g_new_tcp_lock[index], 0, 0); int eth = index; char ip[16] = {0}; InitClientData_new(index); ipaddr = get_local_ip("eth1", ip); PRINTF("open_new_tcp_task index:[%d] ipaddr:[%x]\n", index, ipaddr); RECREATE_TCP_SOCK: bzero(&serv_addr, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(NEW_TCP_SOCK_PORT + index); serv_addr.sin_addr.s_addr = ipaddr; serv_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(serv_sockfd < 0) { ERR_PRN("ListenTask create error:%d,error msg: = %s\n", errno, strerror(errno)); gRunStatus[index] = 0; return NULL; } setsockopt(serv_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); if(bind(serv_sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { ERR_PRN("bind terror:%d,error msg: = %s\n", errno, strerror(errno)); gRunStatus[index] = 0; return NULL; } if(listen(serv_sockfd, 10) < 0) { ERR_PRN("listen error:%d,error msg: = %s", errno, strerror(errno)); gRunStatus[index] = 0; return NULL; } #if 0 if((file_flag = fcntl(serv_sockfd, F_GETFL, 0)) == -1) { ERR_PRN("fcntl F_GETFL error:%d,error msg: = %s\n", errno, strerror(errno)); //gblSetQuit(); return; } if(fcntl(serv_sockfd, F_SETFL, file_flag | O_NONBLOCK) == -1) { ERR_PRN("fcntl F_SETFL error:%d,error msg: = %s\n", errno, strerror(errno)); //gblSetQuit(); return; } #endif PRINTF("sockfd=%d\n", serv_sockfd); while(gRunStatus[index]) { memset(&cli_addr, 0, sizeof(struct sockaddr_in)); len = sizeof(struct sockaddr_in); cli_sockfd = accept(serv_sockfd , (void *)&cli_addr, &len); if(cli_sockfd > 0) { PRINTF("serv_sockfd=%d,cli_sockfd=%d\n", serv_sockfd, cli_sockfd); create_signal_cli_thread(index, cli_sockfd, &cli_addr); PRINTF("sem_wait() semphone inval!!!\n"); } else { if(errno == ECONNABORTED || errno == EAGAIN) { //软件原因中断 usleep(100000); continue; } usleep(3000000); } } for(ipos = 0; ipos < MAX_CLIENT_NUM; ipos++) { if(cli_pthread_id[index][ipos]) { clientsocket = GETSOCK_NEW(index, ipos); if(clientsocket != INVALID_SOCKET) { close(clientsocket); SETSOCK_NEW(index, ipos, INVALID_SOCKET); } if(pthread_join(cli_pthread_id[index][ipos], &ret) == 0) { if(ret == THREAD_FAILURE) { ERR_PRN("drawtimethread ret == THREAD_FAILURE \n"); } } } } }
/*半开扫描*/ static int half_scanner(int port) { char buffer[8192]; int raw_sock; struct sockaddr_in *_dest; int ret; static u_int32_t seq = 0x12345678; struct sockaddr_in dest; int sock_len; int i = 0; struct tcphdr *tcp; u_int32_t current_seq = seq; u_int32_t dst_ip; /*创建用于发送tcp包的原始套接字*/ raw_sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP); if(raw_sock < 0) { perror("socket"); return -errno; } /*获取扫描地址*/ _dest = get_scan_addr(); memcpy(&dest, _dest, sizeof(dest)); //dest = *dest; dest.sin_port = htons(port); /*构造syn包*/ memcpy(&dst_ip, &dest.sin_addr, 4); ret = tcp_syn_pack((struct tcphdr*)buffer, 8192, get_local_ip(raw_sock), dst_ip, 5643, port, seq ++); if(ret < 0) { perror("tcp_syn_pack"); return ret; } //print_pack(buffer, ret); //ip_pack((struct ip*)buffer, IPPROTO_TCP, 255) /*发送*/ ret = sendto(raw_sock, buffer, ret, 0, (struct sockaddr*)&dest, sizeof(dest)); if(ret < 0) { perror("sendto"); return -errno; } /*接收对应的报文*/ sock_len = sizeof(dest); /*尝试接收20次,每次间隔100ms,所以最长延迟2s*/ for(i = 0; i < 40; i ++) { ret = recvfrom(raw_sock, buffer, 8192, MSG_DONTWAIT,(struct sockaddr*)&dest, &sock_len); if(ret < 0 && (errno != EAGAIN) && (errno != EWOULDBLOCK)) { perror("recvfrom"); close(raw_sock); return 0; } else if(ret >= sizeof(struct ip) + sizeof(struct tcphdr)) { /*定位到tcp报文*/ tcp = (struct tcphdr*)(buffer + ((struct ip*)buffer)->ip_hl * 4); /*检测是否是合格的确认报文*/ if(tcp->ack && tcp->seq && tcp->ack_seq == htonl(current_seq + 1)) { scanner_log("主机打开了端口:%10d\n", port); //fflush(stdout); close(raw_sock); return 1; } //printf("recv one %x %x %x\n", tcp->ack, tcp->syn, ntohl(tcp->ack_seq)); } usleep(10 * 1000); } //printf("The host didn't open %d\n", port); //fflush(stdout); close(raw_sock); return 0; }
connection *comm_connect(char *ipaddress, int connections) { int i, port; connection *conn; if (in_thread == NULL) start_threads(); if (connections < 1) return NULL; if (ipaddress == NULL) return NULL; conn = (connection *) malloc(sizeof(connection)); conn->label = strdup(ipaddress); conn->connected = 0; conn->sockets = (out_socket *) malloc(connections * sizeof(out_socket)); conn->num_sockets = connections; // setup the outgoing connections for (i = 0; i < connections; i++) { conn->sockets[i].fd = connect_to_socket(ipaddress, SOPHIA_PORT); set_non_blocking(conn->sockets[i].fd); pthread_mutex_init(&(conn->sockets[i].fd_lock), 0); conn->sockets[i].backlog = 0; conn->sockets[i].done = 0; } conn->connected = 1; // setup the rget connection conn->rget_settings.buffer = cbuf_new(); conn->rget_settings.client_fd = -1; conn->rget_settings.server_fd = -1; while( conn->rget_settings.server_fd < 0 ) { port = randomise_port(); conn->rget_settings.server_fd = listen_on_socket(port); } // comm_send(conn, 1, "void", 1, NULL, NULL, "[RGetRegisterClient \"%d\" \"%s\"]", port, "10.0.0.12"); // REMOTE get_local_ip()); comm_send(conn, 1, "void", 1, NULL, NULL, "[RGetRegisterClient \"%d\" \"%s\"]", port, get_local_ip(conn->sockets[0].fd)); // wait to accept the rget connection while (conn->rget_settings.client_fd < 0) { conn->rget_settings.client_fd = accept(conn->rget_settings.server_fd, NULL, 0); } // add this connect to the inbound subsystem comm_in_add(&(conn->rget_settings)); return conn; }