[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


C# - error- An attempt was made to access a socket in a way forbidden by its access permissions

Posted on 2012-09-06
Medium Priority
Last Modified: 2012-09-11
I have the following error when i run this code, not sure how to fix it...
    Page.Title = "Create an account";
    var sql = string.Empty;
    var firstname = Request["firstname"];
    var lastname = Request["lastname"];
    var username = Request["username"];
    var password = Request["password"];
    var email = Request["email"];
    var email2 = Request["email2"];
            ModelState.AddError("firstname", "Please provide a first name");
            ModelState.AddError("lastname", "Please provide a last name");
            ModelState.AddError("username", "You must provide a user name");
            ModelState.AddError("password", "You must provide a password");
            ModelState.AddError("email", "Please provide your email address");
        if(!email.IsEmpty() && !Functions.IsValidEmail(email)){
            ModelState.AddError("email", "Please provide a valid email address");
        if(email2 != email){
            ModelState.AddError("email2", "Your email addresses must match");
            ModelState.AddFormError("Please fix the errors below before resubmitting the form");
            var db = Database.Open("Classifieds");
            var user = new {FirstName = firstname, LastName = lastname, Email = email};
                var token = WebSecurity.CreateUserAndAccount(username, password, user, true);
                var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
                var message = "<p>Your confirmation code is: " + token + "</p>" +
                    "<p>Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a>" + 
                    " to activate your account.</p>";
                            to: email,	
                            subject: "Please confirm your account", 
                            body: message,
                            isBodyHtml: true
                Roles.AddUsersToRoles(new[]{username}, new[]{"Seller"});
            catch(MembershipCreateUserException ex){
                if(ex.StatusCode == MembershipCreateStatus.DuplicateUserName){
                    ModelState.AddError("username", "That user name is already in use. Please choose another.");
                    ModelState.AddFormError("Please fix the errors below before resubmitting the form");
                    ModelState.AddFormError("Something went wrong. Please try again");
<h2>Create an account</h2>
<p>Use the form below to create an account with the site. Then you can post items for sale and bid on other items. Please ensure that you complete all fields marked with an asterisk *</p>
<form method="post">
            <label for="firstname">First Name*</label>
            <input type="text" id="firstname" name="firstname" value="@firstname" />
            <label for="lastname">Last Name*</label>
            <input type="text" id="lastname" name="lastname" value="@lastname" />
            <label for="username">User Name*</label>
            <input type="text" id="username" name="username" value="@username" />
            <label for="password">Password*</label>
            <input type="password" id="password" name="password" />
            <label for="email">Email*</label>
            <input type="text" id="email" name="email" value="@email" />
            <label for="email2">Re-enter your email*</label>
            <input type="text" id="email2" name="email2" value="@email2" />
            <input type="submit" name="Submit" value="Register" />

Open in new window

Server Error in '/' Application.
An attempt was made to access a socket in a way forbidden by its access permissions
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

Source Error:

Line 43:                     "<p>Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a>" +
Line 44:                     " to activate your account.</p>";
Line 45:                 WebMail.Send(
Line 46:                             to: email,      
Line 47:                             subject: "Please confirm your account",

Source File: c:\webmatrix\Final Code\Chapter12\Classifieds\Account\Register.cshtml    Line: 45

Stack Trace:

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +251
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +279

[WebException: Unable to connect to the remote server]
   System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +6131904
   System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +314
   System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
   System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +322
   System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +146
   System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) +222
   System.Net.Mail.SmtpClient.GetConnection() +50
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1496

[SmtpException: Failure sending mail.]
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1829
   System.Web.Helpers.WebMail.Send(String to, String subject, String body, String from, String cc, IEnumerable`1 filesToAttach, Boolean isBodyHtml, IEnumerable`1 additionalHeaders) +617
   ASP._Page_Account_Register_cshtml.Execute() in c:\webmatrix\Final Code\Chapter12\Classifieds\Account\Register.cshtml:45
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
   System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +68
   System.Web.WebPages.WebPage.ExecutePageHierarchy() +156
   System.Web.WebPages.StartPage.RunPage() +19
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContext context) +249
Question by:yguyon28
LVL 55

Accepted Solution

Jaime Olivares earned 1000 total points
ID: 38374870
This is normally a firewall problem. As a first dirty test, disable your firewall and run your application; then restore it asap. If this is the problem, insert a firewall rule for the conflicting TCP port.

Author Closing Comment

ID: 38388698
It was actually a web config issue... Weird....

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Integration Management Part 2
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question