c# - The results of ports scanning seem to be incorrect while using AsyncCallback -
c# - The results of ports scanning seem to be incorrect while using AsyncCallback -
i'm trying port scan given ip address range of 20 ports. know port 80 open , other closed. code showing ports open.
i'm trying utilize asynchronous tcpclient accomplish port scan.
what wrong here? have missed something?
private void btnstart_click(object sender, eventargs e) { (int port = 80; port < 100; port++) { scanport(port); } } private void scanport(int port) { using (tcpclient client = new tcpclient()) { client.beginconnect(ipaddress.parse("74.125.226.84"), port, new asynccallback(callback), client); } } private void callback(iasyncresult result) { using (tcpclient client = (tcpclient)result.asyncstate) { seek { this.invoke((methodinvoker)delegate { txtdisplay.text += "open" + environment.newline; }); } grab { this.invoke((methodinvoker)delegate { txtdisplay.text += "closed" + environment.newline; }); } } }
this have callback method:
private void callback(iasyncresult result) { using (tcpclient client = (tcpclient)result.asyncstate) { client.endconnect(result); if (client.connected) { this.invoke((methodinvoker)delegate { txtdisplay.text += "open" + environment.newline; }); } else { this.invoke((methodinvoker)delegate { txtdisplay.text += "closed" + environment.newline; }); } } }
the statement:
using (tcpclient client = new tcpclient()) { client.beginconnect(ipaddress.parse("74.125.226.84"), port, new asynccallback(callback), client); }
creates new tcpclient, calls beginconnect, , disposes client, before reaching callback. maintain in mind beginconnect method not blocking. disposal of client should happen in callback, scanport method should this:
private void scanport(int port) { var client = new tcpclient(); seek { client.beginconnect(ipaddress.parse("74.125.226.84"), port, new asynccallback(callback), client); } grab (socketexception) { ... client.close(); } }
in callback should phone call endconnect:
using (tcpclient client = (tcpclient)result.asyncstate) { seek { client.endconnect(result); this.invoke((methodinvoker)delegate { txtdisplay.text += "open" + environment.newline; }); } grab { this.invoke((methodinvoker)delegate { txtdisplay.text += "closed" + environment.newline; }); }
c# winforms asynccallback
Comments
Post a Comment